Using jquery with Closure template

324 views
Skip to first unread message

Jayshanker Nair

unread,
Aug 31, 2012, 8:24:49 AM8/31/12
to closure-temp...@googlegroups.com
I am using Google closure with Jquery . I have a element with id='Header' i want to use the function 
soy.renderElement($('#header'),search.Header,{"name":"jay"});
but its showing me error . If i replace the same code with document.getElementById('header')
then it is working . Can anyone help me please...............

Adam

unread,
Aug 31, 2012, 10:44:37 AM8/31/12
to closure-temp...@googlegroups.com
My honest advice is that you don't use Soy templates yet. Why? Because I think you should spend a few hours for a few days getting to know Javascript, jQuery, and how the DOM works before you stick an abstraction like Soy and renderElement() on- top of it. Otherwise, you'll continue treating it like a black box, not understanding it, and then being frustrated over and over when your box doesn't work as you expected it to. JS is pretty transparent - you can take a look at the code for any page on the web (and for soy.renderElement) to see how it works from within your browser. Paul Irish has a lot of videos about how to use Chrome's Developer Tools to do this - worth Googling.


soy.renderElement = function(element, template, opt_templateData) {
  element.innerHTML = template(opt_templateData);
};

The reason jQuery isn't working for you is that jQuery doesn't return DOM nodes (aka the native objects the browser gives you to represent an element in the document). jQuery returns JS objects which wrap DOM nodes. soy.renderElement expects a DOM node to be the first argument.

When you set the innerHTML property on a DOM element, the browser changes the structure of the document to match your string. When you set the innerHTML property of any other JS object (including jQuery objects), it doesn't do anything except save that HTML string as a new property on the object in JS. It has no affect on the HTML document.

So you are taking a JS object from jQuery that looks like:
{
  length : 1,
  0 : *the DOM node*
 ...
}
and turning it into: 
{
  length : 1,
  0 : *the DOM node*,
  innerHTML : *a string of HTML*
 ...
}

Since jQuery allows you to access the wrapped DOM nodes using array notation, where [0] returns the first matched element, you can use $('#header')[0] to get a reference to your DOM node and pass it to soy. 

soy.renderElement($('#header')[0],search.Header,{"name":"jay"});

Jayshanker Nair

unread,
Sep 1, 2012, 2:39:31 AM9/1/12
to closure-temp...@googlegroups.com
Thanks Adam i will take your suggestion and will spend some more time on understanding Javascript and Jquery............
Reply all
Reply to author
Forward
0 new messages