在handlebarsjs中执行字符串包含检查的方法是什么?

huangapple go评论52阅读模式
英文:

How to perform string contains check in handlebarsjs

问题

如何在Handlebars.js中在if块内执行字符串包含检查

{{ if loop_var.imageUri }}

  # 如果 loop_var.imageUri 包含 foo
    <img width="50" height="50" src="{{loop_var.imageUri}}"/>
  # 否则
    <img width="150" height="150" src="{{loop_var.imageUri}}"/>
  # 结束

{{ else }}

{{ end }}
英文:

How to perform string contains check in handlebarsjs within the if block

\{{ if loop_var.imageUri }}
  
      # if loop_var.imageUri contains foo
        &lt;img width=&quot;50&quot; height=&quot;50&quot; src=&quot;{{loop_var.imageUri}}&quot;/&gt;
      # else
        &lt;img width=&quot;150&quot; height=&quot;150&quot; src=&quot;{{loop_var.imageUri}}&quot;/&gt;
      # end

\{{ else }}

\{{ end }}

答案1

得分: 1

Handlebars没有提供用于在两个字符串上执行包含比较的帮助器,但你可以轻松创建自己的帮助器。它需要是一个块帮助器,这样你就可以为不匹配的情况添加{{else}}分支。

const template = Handlebars.compile(`
{{#if loop_var.imageUri}}
  {{#ifContains loop_var.imageUri 'foo'}}
    <img width="50" height="50" src="{{loop_var.imageUri}}"/>
  {{else}}
    <img width="150" height="150" src="{{loop_var.imageUri}}"/>
  {{/ifContains}}
{{/if}}
`);

Handlebars.registerHelper('ifContains', function (source, subString, options) {
  if (source.indexOf(subString) > -1) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

const data = {
  loop_var: {
    imageUri: '/my/foo/image/'
  }
};

const output = template(data);

document.body.innerHTML = output;
英文:

Handlebars has no helper to do a contains comparison on two strings, but you can easily create your own. It would need to be a Block Helper so that you can add the {{else}} branch for cases of non-matches.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const template = Handlebars.compile(`
{{#if loop_var.imageUri}}
  {{#ifContains loop_var.imageUri &#39;foo&#39;}}
    &lt;img width=&quot;50&quot; height=&quot;50&quot; src=&quot;{{loop_var.imageUri}}&quot;/&gt;
  {{else}}
    &lt;img width=&quot;150&quot; height=&quot;150&quot; src=&quot;{{loop_var.imageUri}}&quot;/&gt;
  {{/ifContains}}
{{/if}}
`);

Handlebars.registerHelper(&#39;ifContains&#39;, function (source, subString, options) {
  if (source.indexOf(subString) &gt; -1) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

const data = {
  loop_var: {
    imageUri: &#39;/my/foo/image/&#39;
  }
};

const output = template(data);

document.body.innerHTML = output;

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月11日 19:48:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76227319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定