gstackoverflow
gstackoverflow

Reputation: 36966

How does underscore replace variables?

I have following row in code:

 terminalsListHtml += this.compiled(_.extend(this.terminals[i], {clazz: 'all'}, obj));

Behaviour of execution this row is surprising for me.

I evaluate argument value of this.compiled method.
It looks like this:

enter image description here

more details:

compiled: _.template($('#terminal-template').text())

enter image description here Lets return to first row whos result is surprising for me:

it returns following result:

this.compiled(_.extend(this.terminals[i], {clazz: 'all'}, obj));
"
    <li data-terminal-id="201" class="">
        <label>
             
          <input type="checkbox" name="terminal" class="all" data-terminal-id="201" />
            <a href="#" title="" class="image"><img
                    src="getMediumThumbnail/1"
                    alt=""/></a>   
            <h3>Second
                <small>Lenina, 5</small>
            </h3>
            <p>Second</p>

            <p class="count">Проходимость: <span>10</span> чел./час</p>

            <p class="count">Стоимость: <span>5</span> руб./час</p>

            <p class="count">Количество свободных слотов: <span>10</span> </p>
        </label>
    </li>
"

As we can see {{imageId}} was replaced with 1.

I don't understand where does this 1 takes.
Please clarify.

P.P.S.

Sorry for screenshots instead of copied code. I wanted to pasted code but it render bad.

Upvotes: 1

Views: 175

Answers (1)

pawel
pawel

Reputation: 36995

this line:

 compiled: _.template($('#terminal-template').text())

turns a string (the text contents of an element with id="terminal-template") into a function that can be evaluated later: http://underscorejs.org/#template

then calling this.compiled( object ) renders the template (calls te previously compiled template function) with the object set as the context, so if the object has a key imageId it will be substituted in place of {{imageId}} in the template string. It looks like the object returned from _.extend(this.terminals[i], {clazz: 'all'}, obj) has that key and it is equal to 1.

Judging by the screenshot you have provided maybe it should produce <img src="getMediumThumbnail/undefined" ... />.
But the imageId may come from the object's prototype or even from the global scope (which has been confirmed in the discussion in comments: window.imageId == 1).

EDIT: what is strange is that underscore only reaches the global scope when _.templateSettings is used to change the syntax: http://jsfiddle.net/hoy9ga0d/ - using default <%= variable %> doesn't render a global variable, but {{ variable }} does.

Upvotes: 1

Related Questions