06.05.2013 Views

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>JavaScript</strong> Theming<br />

}<br />

var values = ['content','submitted','taxonomy','links'];<br />

for (var i = 0; i < values.length; ++i) {<br />

var value = values[i];<br />

if (node[value]) {<br />

tpl.find('.' + value).html(node[value]);<br />

}<br />

else {<br />

tpl.find('.' + value).hide();<br />

}<br />

}<br />

// Now we dump the template to a string.<br />

out = tpl.parent().html();<br />

}<br />

return out;<br />

The template has now been populated. However, like all theme functions, this must<br />

return the results neither as a <strong>jQuery</strong> object, nor as HTML elements, but as a string.<br />

To do this, we call tpl.parent().html(). This goes to the very root of the template<br />

<strong>and</strong> retrieves the HTML as a string. At the end of this function, the string is returned.<br />

Using the template system<br />

We now have a basic template system. We can very quickly mock up a new function<br />

to test out our template-based theme:<br />

function addNode() {<br />

var node = {<br />

title: "New Node",<br />

content: "<strong>JavaScript</strong> created this node!",<br />

nodeUrl: 'http://drupal.org'<br />

};<br />

$('.node:last').after(<strong>Drupal</strong>.theme('node', node));<br />

<strong>Drupal</strong>.attachBehaviors();<br />

}<br />

The addNode() function creates a new node object with a title, content, <strong>and</strong> a<br />

nodeUrl. It then finds the node section <strong>and</strong> adds the new node to the end of the<br />

existing list of nodes. For example, on the front page, it would add it at the bottom of<br />

the page.<br />

Notice that we call <strong>Drupal</strong>.theme('node', node) to invoke the <strong>Drupal</strong>.theme.<br />

prototype.node() function that we just defined, <strong>and</strong> pass it our new node object.<br />

Finally, since we have just altered the DOM, we need to run the <strong>Drupal</strong>.<br />

attachBehaviors() function to make sure any new elements get evaluated by the<br />

behaviors system.<br />

[ 192 ]<br />

This material is copyright <strong>and</strong> is licensed for the sole use by Richard Ostheimer on 18th June 2009<br />

2205 hilda ave., , missoula, , 59801

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!