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.68k stars 340 forks source link

strange behaviour of "if" block inside href attribute #233

Closed dgavrus closed 10 years ago

dgavrus commented 10 years ago

So, I have next code into href string:

    <a href="{{:pageName}}/page/{{if pageNumber === "next"}}
                                                        {{:current + 1}}
                                                    {{else pageNumber === "prev"}}
                                                        {{:current - 1}}
                                                    {{else}}
                                                        {{:pageNumber}}
                                                    {{/if}}">{{:pageNumber}}</a>

and data:

     {
        "current":5,
        "pageNumber":"next",
        "pageName":"transactions"
    }

output of this script is: <a href="#transactions/page/<script type=">6">next</a>

If I insert instead all "if else" block simple {{:current + 1}} it's working fine, but with this block it doesn't work

BorisMoore commented 10 years ago

Are you using JsViews, or just JsRender?

If just JsRender, then you can put {{if}} blocks within element markup - but clearly you have to deal with using appropriate string delimiters, ' or ".

So at at least change to ' and avoid newlines to avoid incorrectly terminating your string within the xxx string for href="xxx"

 <a href="{{:pageName}}/page/{{if pageNumber === 'next'}}{{:current + 1}}{{else pageNumber === 'prev'}}{{:current - 1}}{{else}}{{:pageNumber}}{{/if}}">{{:pageNumber}}</a>

You can also use ternary expressions:

 <a href="{{:pageName}}/page/{{:pageNumber === 'next' ? current + 1 : (pageNumber === 'prev' ?current - 1 : pageNumber)}}">{{:pageNumber}}</a>

If using JsViews, you cannot nest JsViews tags like {{if ...}} within attribute markup. Use data-link="href{:...}". Take a look at the tutorial sequence, http://www.jsviews.com/#samples/data-link - and in particular: http://www.jsviews.com/#samples/data-link/attributes.

Also generally it is better to encapsulate complex logic in helper functions, like:

 <a href="{{:~getHrefFromPage(pageName, pageNumber, current)">{{:pageNumber}}</a>