Search code examples
jsviews

JSViews Merge id with string to get unique id


I have an array which I am iterating over using

{{for}}

in the loop, I am creating various elements, one of which I need to generate unique Ids for include one of the variables in the array (Id)

so for example:

<div id="post-123">...

I have tried:

<div data-link="id{post-:Id}">...

and

div data-link="id{'post-':Id}">...

and

<div id="post-" data-link="id{merge:Id}">...

however none of these work.

if I omit the string and just use:

<div data-link="id{:Id}">...

it sets the Id just fine. Can anyone see what I am doing wrong?


Solution

  • These links talk of data-linking to attributes:

    The standard syntax is

    data-link="attributeName{:dataPathOrExpression}"
    

    In your case attributeName is id.

    dataPathOrExpression can be any expression, so here you need it to be the Id value concatenated with (preceded by) the string 'post-', so you need to write:

    <div data-link="id{:'post-' + Id}">...
    

    or, equivalently

    <div data-link='id{:"post-" + Id}'>...
    

    You don't want to put anything between the { and :. The tag is {: (http://www.jsviews.com/#assigntag) - and the only thing you can put between those characters is a converter name such as myCvt, as in: id{myCvt:...}.


    That said, if your Id values are not changing observably, then you don't need to data-link the id and you can instead write:

    <div id="post-{{:Id}}">...
    

    just as you would if you were rendering the template as a JsRender template, without data binding.