xan
xan

Reputation: 4696

Including HTML in javascript

I've to use loads of textin javascript as templates. Its too bad (I know). However, when I fetch the results through Ajax/PHP/JSON, it was elegant but made the fetching of results a little slow. I was displaying the matter in a popup. So again I'm back to templates. My question is: "Is there any tool that can automatically parse the HTML code into javascript".

Example: In HTML, the following code

<ul class="tabs">
    <li><a href="#" name="#tab1">Introduction</a></li>
    <li><a href="#" name="#tab2">Round</a></li>
    <li><a href="#" name="#tab3">Rules</a></li>
</ul>

becomes in javascript as:

'<ul class="tabs">'+
    '<li><a href="#" name="#tab1">Introduction</a></li>'+
    '<li><a href="#" name="#tab2">Round</a></li>'+
    '<li><a href="#" name="#tab3">Rules</a></li>'+
'</ul>'+

Are there any other ways?

Upvotes: -1

Views: 134

Answers (3)

Tim M.
Tim M.

Reputation: 54417

Here's an example of how to do it using hidden <code> elements. Facebook does this extensively.

HTML:

<div>here is some normal content</div>
<code class="template" id="template1"> 
  <div>this is a template</div>
</code>

<div id="renderedTemplate"></div>

Script:

var template = $("#template1").html();
var templateOutput = $("#renderedTemplate");

for( var i = 0; i < 10; i++ ){
    templateOutput.append(template);  
}

CSS:

.template {
  display: none;
}

However, since you aren't Facebook, make your life easier and use something like Handlebars as @Shmiddty suggested. It uses a similar approach, but adds powerful templating capabilities into the mix, rather than verbatim string insertion.

Upvotes: 0

Brian Salta
Brian Salta

Reputation: 1576

<button>Show it</button>
<p style="display: none">Hello 2</p>

$("button").click(function () {
    $("p").show("slow");
});

http://api.jquery.com/show/

Upvotes: 0

Louis XIV
Louis XIV

Reputation: 2224

Put you content in an hidden div and load it with .html() method of jquery.

Upvotes: 0

Related Questions