Javascript 如何使用 Handlebars.js 小写字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9011228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:23:15  来源:igfitidea点击:

How do I lowercase a field using Handlebars.js?

javascripthandlebars.js

提问by Eric the Red

I want to do something like this:

我想做这样的事情:

{{user.name.toLowerCase()}}

but I get this error:

但我收到此错误:

Error: Parse error on line X:
...tatus {{user.name.toLowerCase()}}">  
-----------------------^
Expecting 'ID', got 'undefined'

采纳答案by Eric the Red

I created the following helper, but I'm curious if there's a better solution out there.

我创建了以下助手,但我很好奇是否有更好的解决方案。

Handlebars.registerHelper('toLowerCase', function(value) {
    if(object) {
        return new Handlebars.SafeString(value.toLowerCase());
    } else {
        return '';
    }
});

回答by Cyril N.

As simply explained in the doc:

正如文档中简单解释的那样:

Handlebars.registerHelper('toLowerCase', function(str) {
  return str.toLowerCase();
});

And just use it like this :

就像这样使用它:

<h1>By {{toLowerCase author}}</h1>

回答by senbrow

If you're just trying to display some text as lowercased in HTML (regardless of whether or not it's generated by handlebars), you can use CSS and apply text-transformlike so:

如果你只是想在 HTML 中显示一些小写的文本(不管它是否由把手生成),你可以使用 CSS 并应用文本转换,如下所示:

.css-class-here {
    text-transform: lowercase;
}

回答by f1ames

Previous answer from @Eric seems not to work now, my solution is very similar, but probably the definition of helpers changed a little in new versions of handlebars:

@Eric 以前的回答现在似乎不起作用,我的解决方案非常相似,但在新版本的把手中,助手的定义可能有所改变:

Handlebars.registerHelper('tolower', function(options) {
    return options.fn(this).toLowerCase();
});

and in the template

并在模板中

<img src="/media/images/modules/{{#tolower}}{{name}}{{/tolower}}.png"...

Cheers

干杯

回答by yonib

Doesn't hurt to also check and make sure it is a string and if not return nothing.

也可以检查并确保它是一个字符串,如果不是,则不返回任何内容也无妨。

Handlebars.registerHelper('lowercase', function (str) {
  if(str && typeof str === "string") {
    return str.toLowerCase();
  }
  return '';
});

Usage :

用法 :

// now let's pass a string or variable to our helper
{{lowercase 'MY NAME IS'}}

Output :

输出 :

my name is