2014-04-18 54 views
0

我想學習JSRender。是否可以根據條件呈現子模板?例如,如果#index = 1或2,則渲染模板A(如果是3或4)渲染模板B?JSRender - 如何有條件地渲染子模板

+0

'{{if index == 1}} <! - RENDER THIS - > {{> elseif index ==}} {{/ if}}' –

+0

謝謝,太好了。在這種情況下調用子模板的語法是什麼? – user2427285

+0

子模板的意思是什麼?提示您的代碼 –

回答

1

下面是正確的語法 - 以及下面的一些文檔鏈接。

<script id="tmplFeaturePanel1" type="text/x-jsrender"> 
    {{for List}} 
     {{if #index == 1 || #index == 2}} 
      {{include tmpl="#test1or2"/}} 
     {{else #index === 3 || #index === 4 }} 
      {{include tmpl="#test3or4"/}} 
     {{else}} 
      {{include tmpl="#testOther"/}} 
     {{/if}} 
    {{/for}} 
</script> 

或更簡潔的語法,其中工程一樣的是:

<script id="tmplFeaturePanel2" type="text/x-jsrender"> 
    {{for List}} 
     {{if #index == 1 || #index == 2 tmpl="#test1or2"}} 
     {{else #index === 3 || #index === 4 tmpl="#test3or4"/}} 
     {{else tmpl="#testOther"/}} 
     {{/if}} 
    {{/for}} 
</script> 

其中在兩種情況下,參照的模板可能是:

<script id="test1or2" type="text/x-jsrender"> 
    1or2 {{:name}} 
</script> 

<script id="test3or4" type="text/x-jsrender"> 
    3or4 {{:name}} 
</script> 

<script id="testOther" type="text/x-jsrender"> 
    Other: {{:name}} 
</script> 

BTW注意{{elseif ...}}{{else if ...}}是不正確的語法。 其實{{else someExpression}}作爲一個elseif。 {{else}}作爲其他人。

+0

感謝您提供清晰有用的答案。這是我將要使用的代碼的改進。 – user2427285