简体   繁体   English

Ember.js 包含字符串助手

[英]Ember.js contains string helper

I'm looking to something like this in template file:我在模板文件中寻找这样的东西:

{{#contains 'invalid' item.name}}
  something
{{/contains}}

Basically check if the string contains a certain word基本上检查字符串是否包含某个单词

Not sure how the helper function would look like, but this is a random guess although I don't think this complies to above code.不确定助手 function 的外观如何,但这是一个随机猜测,尽管我认为这不符合上述代码。

import Helper from 'ember-helper';

export function containsHelper([substr, str]) {
 return str.contains(substr)
}

export default Helper.helper(containsHelper);

Something like that but how do I do it in a Ember.js helper such that I can use it in a template file?类似的东西,但我如何在 Ember.js 助手中做到这一点,以便我可以在模板文件中使用它?

Thanks!谢谢!

You've guessed it pretty much right.你已经猜对了。 This would be your implementation:这将是您的实现:

// app/helpers/contains.js

import { helper } from '@ember/component/helper';

function contains([substr, str]) {
  return str.contains(substr)
}

export default helper(contains);

and then in your template:然后在您的模板中:

{{contains 'invalid' item.name}}

or rather更确切地说

{{#if (contains 'invalid' item.name)}}
 your stuff
{{/if}}

Here's the doc是文档

In addition to @Andrey's answer, I'm in-progress of getting https://github.com/glimmerjs/glimmer-vm/pull/1348 merged, which allows you to use "just plain functions" as helpers (RFC: https://github.com/emberjs/rfcs/pull/756 )除了@Andrey 的回答,我正在合并https://github.com/glimmerjs/glimmer-vm/pull/1348 ,这允许您使用“只是普通函数”作为助手(RFC: https ://github.com/emberjs/rfcs/pull/756 )

There is a polyfill you can install: https://github.com/NullVoxPopuli/ember-functions-as-helper-polyfill您可以安装一个polyfill:https://github.com/NullVoxPopuli/ember-functions-as-helper-polyfill

npm install ember-functions-as-helper-polyfill

and then you could do this:然后你可以这样做:

export default class MyComponent extends Component {
  contains = (substr, str) => str.includes(substr);
}
{{#if (this.contains 'invalid' item.name)}}
  something
{{/if}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM