Handlebarsjs check if a string is equal to a value

后端 未结 13 761
挽巷
挽巷 2020-12-08 18:23

Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can\'t seem to find anything relevant to this in the Handlebars r

相关标签:
13条回答
  • 2020-12-08 19:01

    In Handlebars, the parenthesis are used to invoke the first item listed as a function, using (optional) subsequent items as parameters. So, the syntax from Ember CAN be used without Ember, provided you can set the context yourself. For example:

        context.eq = function(param1, param2) {
            return param1 === param2;
        }
    
        context.notEq = function(param1, param2) {
            return param1 !== param2;
        }
    

    Once you do that, you can use the standard {{#if}} and {{#unless}} block operations:

    {{#if (eq someVar "someValue") }}
    

    Be careful of switching contexts with {{with}} or when using inline partials. You can lose track of your defined "eq" function. The guaranteed way to work, regardless of new contexts:

    {{#if (@root.eq someVar "someValue") }}
    
    0 讨论(0)
  • 2020-12-08 19:01

    Try:

    {{#is item.status "complete"}} ... {{/is}}

    0 讨论(0)
  • 2020-12-08 19:02

    The previous answer with match does not work for me, I get an error on the if statement (something like 'must have only one argument').

    However, I just found the solution here without having to write any more helper:

    {{#if (eq person "John")}} hello {{/if}}
    
    0 讨论(0)
  • 2020-12-08 19:02

    Handlebars has a conditional operator called 'equal' that takes two parameters:

    1.The variable

    2.what your checking if the variable contains.

    For examples, to check if 'status' contains 'Full Time':

    {{#equal status "Full Time"}}  //status is the variable and Full Time is the value your checking for.
        code to be executed
    {{else}}
        code to be executed
    {{/equal}}
    
    0 讨论(0)
  • 2020-12-08 19:10

    I had same difficulty as OP and decided to just sublet the call to Javascript rather than trying to bend Handlebars to my will ...

    Javascript function (in global scope) -

    function jsIfElse(compare1, compare2, trueResponse, falseResponse) {
      document.write((compare1 == compare2) ? trueResponse : falseResponse);
    }
    

    Handlebars snippet -

    <select multiple id="batter_player_team">
      {{#each teamNamesForFilter}}
      <option value="{{this.id}}">                     <script>jsIfElse('{{this.is_active}}','Y','{{this.name}} *', '{{this.name}}');</script>
      </option>
       {{/each}} 
    </select>
    
    0 讨论(0)
  • 2020-12-08 19:15

    Just came to this post from a google search on how to check if a string equals another string.

    I use HandlebarsJS in NodeJS server-side, but I also use the same template files on the front-end using the browser version of HandlebarsJS to parse it. This meant that if I wanted a custom helper, I'd have to define it in 2 separate places, or assign a function to the object in question - too much effort!!

    What people forget is that certain objects have inherit functions that can be used in the moustache template. In the case of a string:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

    An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.

    We can use this method to return either an array of matches, or null if no matches were found. This is perfect, because looking at the HandlebarsJS documentation http://handlebarsjs.com/builtin_helpers.html

    You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.

    So...

    {{#if your_string.match "what_youre_looking_for"}} 
    String found :)
    {{else}}
    No match found :(
    {{/if}}
    

    UPDATE:

    After testing on all browsers, this doesn't work on Firefox. HandlebarsJS passes other arguments to a function call, meaning that when String.prototype.match is called, the second argument (i.e. the Regexp flags for the match function call as per above documentation) appears to be being passed. Firefox sees this as a deprecated use of String.prototype.match, and so breaks.

    A workaround is to declare a new functional prototype for the String JS object, and use that instead:

    if(typeof String.includes !== 'function') {
        String.prototype.includes = function(str) {
            if(!(str instanceof RegExp))
                str = new RegExp((str+'').escapeRegExp(),'g');
            return str.test(this);
        }
    }
    

    Ensure this JS code is included before you run your Handlebars.compile() function, then in your template...

    {{#your_string}}
        {{#if (includes "what_youre_looking_for")}} 
            String found :)
        {{else}}
            No match found :(
        {{/if}}
    {{/your_string}}
    
    0 讨论(0)
提交回复
热议问题