I've been updating some code that was built using jQuery Templates, but since jQuery Templates has been discontinued, I've decided to migrate my code to use JsRender.
The syntax is close enough for the most part that translating existing templates is straightforward enough. For the most part it's updating to the new mustache-like bracket syntax and changing variables from ${var} to {{=var}}. However, there was one thing that was tripping me up—simple conditional statements.
JsRender uses the mustache like "codeless" syntax for conditions:
{{#if varName}}output{{/if}}
This fine if varName is a truthy statement, but what if you need to check if varName is equal to a specific value? Having gone through all the JsRender sample code, it appeared the only way to accomplish any kind of comparison conditional statement was to use custom code. This syntax ends up being very ugly and verbose. Here's an example of writing an attribute dynamically based on the value of a variable named varName :
<div class="base{{* if($view.data.varName == 'None'){ result += ' none'; } }}">{{=varName}}</div>
This seems overly complicated for such a simple comparison. I figured there had to be a better way.
After digging through the code, I found there's some undocumented features of the if tag. You can actually use the following syntax to do the same thing:
<div class="base{{#if varName eq='None')}} none{{/if}}">{{=varName}}</div>
While this syntax ends up being pretty close to jQuery Templates, it uses the "hash" functionality of JsRender's custom tags. The odd looking part is that you need the equal sign between the conditional operator and the value. Other operators include:
I actually would prefer to see "lte" and "gte" used for the "or equal" functions, so I've added that to a ticket.
So, while the syntax isn't ideal, it's certainly better than using using the code syntax. Since the project is still in development, it possible the syntax will change.
4 Comments
Comments for this entry have been disabled.