How do I lowercase a field using Handlebars.js?

前端 未结 5 1062
我寻月下人不归
我寻月下人不归 2021-02-01 14:27

I want to do something like this:

{{user.name.toLowerCase()}}

but I get this error:

Error: Parse error on line X:
...tatus {{us         


        
相关标签:
5条回答
  • 2021-02-01 14:30

    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
    
    0 讨论(0)
  • 2021-02-01 14:35

    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 '';
        }
    });
    
    0 讨论(0)
  • 2021-02-01 14:36

    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>
    
    0 讨论(0)
  • 2021-02-01 14:49

    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:

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

    and in the template

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

    Cheers

    0 讨论(0)
  • 2021-02-01 14:55

    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-transform like so:

    .css-class-here {
        text-transform: lowercase;
    }
    
    0 讨论(0)
提交回复
热议问题