BorisMoore / jsrender

A lightweight, powerful and highly extensible templating engine. In the browser or on Node.js, with or without jQuery.
http://www.jsviews.com
MIT License
2.67k stars 339 forks source link

How to use if construction with parameter #337

Closed sharepointmike closed 5 years ago

sharepointmike commented 6 years ago

I call my template like this:

`$("#ChangeCurrentCycleDiv").html(
    $("#UpdateTemplate").render(CurrentCyclefields,
            {ButtonName: "btnChangeCycle",
             Titel: "Change Current Cycle",
             FormID: "ChangeCurrentCycleForm",
             PanelSize: "ms-Panel ms-Panel--Max" }, 
            true)
);`

This worked fine but now I added the "PanelSize" parameter which sometimes is used and sometimes is not. So in my template I try to do this:

<div {{if {{:~PanelSize}} }} class={{:~PanelSize}} {{else}}class="ms-Panel ms-Panel--xxl"{{/if}}>

But what kind of variant I use, it's not working (wrong syntax errors). What is the correct syntax to do this? So if the parameter is send, it is used. Otherwise the default is used. Thanks a lot for the help

BorisMoore commented 6 years ago

The syntax for {{if}} is {{if ~PanelSize}} .... {{else}} ... {{if}}

http://www.jsviews.com/#iftag

So in your case it would be

<div {{if ~PanelSize}}class="{{:~PanelSize}}"{{else}}class="ms-Panel ms-Panel--xxl"{{/if}}>

Or better, perhaps:

<div class="{{if ~PanelSize}}{{:~PanelSize}}{{else}}ms-Panel ms-Panel--xxl{{/if}}">

Alternatively you can use ternary expressions:

<div class="{{:~PanelSize?~PanelSize:'ms-Panel ms-Panel--xxl'}}">

or even simpler with a ||

<div class="{{:~PanelSize||'ms-Panel ms-Panel--xxl'}}">

If you are using JsViews data-linking, you can instead use a data-linked expression:

<div data-link="class{:~PanelSize||'ms-Panel ms-Panel--xxl'}">
sharepointmike commented 6 years ago

Thanks a lot Boris!!