0

I have a model containing attributes in a multidimensional array. In the template function of the view, I want to unpack this array but I'm not sure how to accomplish this with underscore.js. I've looked around on google, but I can't seem to find a straightforward example.

For Example, here is a multidimensional array:

array(
    "elementTag" => "li",
    "elementClass" => "dashboard",
    "elementContent" => array(
        "elementTag" => "a",
        "elementContent" => "The Value I want to Display!!!",
        "href" => "#home"
    )
)

If my template: looks like this:

template: _.template('<<%= elementTag %> class="<%= elementClass %>">...</<%= elementContent %>>') 

How would I display the value of elementContent ?:

The Value I want to Display!!!

2 Answers 2

2

JavaScript uses dot notation to access properties of objects.

For example, you posted your array as it would appear in php, in JavaScript you would create that structure as follows:

var myObject = {
    "elementTag": "li",
    "elementClass": "dashboard",
    "elementContent": {
        "elementTag": "a",
        "elementContent": "The Value I want to Display!!!",
        "href": "#home"
    }
}

You can then pass that to a constructor on your backbone model, which is what the collection does internally when you call fetch/reset etc.

var model = new ElementModel(myObject)

model.get('elementClass') // returns "dashboard"
model.get('elementContent') // returns the element content object
model.get('elementContent').elementTag // returns the "a"

var myObject = model.toJSON() // returns the object in the same format as above

myObject.elementClass // "dashBoard"
myObject.elementContent.elementTag // "a"

Commonly in backbone you pass the result of model.toJSON() to the underscore template, so as @fencliff rightly answered, all of the properties of your object are available in the template in the format

<%= elementTag %>
<%= elementClass %>
<%= elementContent.elementContent %>
// etc.
Sign up to request clarification or add additional context in comments.

Comments

1

Unless I misunderstood you, <%= elementContent.elementContent %> should do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.