问题
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.
Basically I want to change a button's text based on the value of a handlebars expression, but I'm not sure how to do so without being able to add logic operators in my {{#if}} statement.
Basically, when the value of {{form.target}} is equal to "new", I want the button text to say "Save", and if the value is equal to "edit', I want the text to say "Save Changes".
This is the way I would write it if I could:
<button>
{{#if {{form.target}} == 'new'}}
Save
{{#else if {{form.target}} == 'edit'}}
Save Changes
{{/if}}
</button>
Obviously I'm way off base here, so I was hoping someone could point me to the correct way of doing this?
回答1:
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);
}
});
回答2:
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.
回答3:
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>
来源:https://stackoverflow.com/questions/50712361/logic-in-handlebars-if-else-statement