javascript 是否可以在车把模板中嵌套 if/else 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17945736/
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-10-27 10:12:00  来源:igfitidea点击:

Is it possible to nest if/else statements in handlebars templates?

javascripthtmltemplateshandlebars.js

提问by Henry Wilson

I'm wondering if it is possible to nest multiple if/else statements using handlebars? All my attempts so far have resulted in compile errors, what I'd like to do is as follows:

我想知道是否可以使用把手嵌套多个 if/else 语句?到目前为止,我所有的尝试都导致了编译错误,我想做的如下:

{{if address}}
    <ul>
    <li>address.line1</li>
    <li>address.line2</li>
    {{if address.line3}}<li>address.line3</li>{{/if}}
    {{if address.line4}}<li>address.line4</li>{{/if}}
{{else}}
   No address given
{{/if}}

Is what I'm attempting here achievable? It always results in parser errors, thusfar I've got around it by writing a helper to deal with spitting out the address (which deals with conditionality of line3/line4 in javascript):

我在这里尝试的东西可以实现吗?它总是导致解析器错误,到目前为止,我已经通过编写一个帮助程序来处理吐出地址(它处理 JavaScript 中 line3/line4 的条件)来解决它:

{{if address}}
    {{formatAddress address}}
{{else}}
   No address given
{{/if}}

While this works, it would be nice not to have to write a helper function for every instance of this sort of simple conditionality.

虽然这是有效的,但最好不必为这种简单条件的每个实例编写一个辅助函数。

回答by dcodesmith

I believe ifs need a preceding #

我相信 ifs 需要一个前面的 #

Try this.

试试这个。

{{#if address}}
    <ul>
        <li>address.line1</li>
        <li>address.line2</li>
        {{#if address.line3}}<li>address.line3</li>{{/if}}
        {{#if address.line4}}<li>address.line4</li>{{/if}}
    </ul>
{{else}}
   No address given
{{/if}}