Logic in Handlebars if/else statement?

后端 未结 3 854
清歌不尽
清歌不尽 2020-12-22 12:03

Forgive me for the stupid question, I know you\'re not supposed to put logic in handlebars expressions, but I\'m new to this and I\'m not sure how to get around it.

相关标签:
3条回答
  • 2020-12-22 12:44

    You are right that the common guidance is to limit the use of logic in your views. Sometimes you will need it, but in this example we can go without.

    Handlebars is referencing values that are passed into the template function as its context. You can use some branching logic to assign a variable to the value you need, then in the template reference that value directly.

    The details will vary depending on how you are using Handlebars, but here's an example:

    <script id="some-template" type="text/x-handlebars-template">
        <button>
            {{formSubmissionText}}
        </button>
    </script>
    
    <div id="my-app"></div>
    
    <script>
        // create `template` function that will render the view
        let source = document.getElementById("some-template").innerHTML;
        let template = Handlebars.compile(source);
    
        // construct the context we'll bind to our template
        let form = getForm(); // change this to match your use
        let formSubmissionText = "Save";
        if (form.target === "edit") {
            formSubmissionText = "Save Changes";
        }
    
        let context = {
            formSubmissionText: formSubmissionText
        };
    
        // render the template
        let html = template(context);
        document.getElementById("my-app").innerHTML = html;
    </script>
    
    0 讨论(0)
  • 2020-12-22 12:49

    You can register a helper

    <button>
        {{#equals form.target "new"}}
            Save
        {{else}}
            {{#equals form.target "edit"}}
                Save Changes
            {{/equals}} 
        {{/equals}} 
    </button>
    
    Handlebars.registerHelper("equals", function(string1 ,string2, options) {
        if (string1 === string2) {
            return options.fn(this);
        } else {
            return options.inverse(this);
        }
    });
    
    0 讨论(0)
  • 2020-12-22 12:58

    Ideally you'd want to create a property on the form object that would give you the info you need, e.g. form.targetIsNew and/or form.targetIsEdit. If you set that beforehand then you can use it in your if/else block.

    So before rendering the handlebars template, set one of those properties:

    form.targetIsNew = form.target == 'new';
    

    You can also use block helpers if things are more complex.

    0 讨论(0)
提交回复
热议问题