JQuery - replace one line with another in .load-ed html?

I am loading html snippet with

$("#TemplateDump").load("Themes/default.template", function() { processTemplate() })

      

In the html i load

<div>
`hello ##name##, your age is ##age##. 
your page is <a href="##website##">here</a>
</div>

      

I need to replace ## placeholders with "joe", "112" and "www.whatever.com". Is there a more jquery way to do this rather than using direct javascript.replace? Are there plugins to replace placeholders around? using .replace in IE on url placeholder just doesn't work. I do not know why. By the way, templates cannot be changed.

0


source to share


2 answers


Implementing a simple templating system in vanilla javascript isn't too hard.

var myValues = {
    name : 'Joe',
    age : '112',
    website: 'http://www.whatever.com'
};
var myString = "hello ##name## ..."; // etc

for (var key in myValues) {
    myString.replace(new RegExp("##" + key + "##", g), myValues[key]);
}

      



Just make sure you run this script in HTML before it gets inserted into your document. You might want to use a different AJAX feature than load()

maybe get()

?

$.get(
    'themes/default.template',
    {},
    function (data) {
        data = processTemplate(data);
        $('#templateDump').html(data);
    }
);

      

+1


source


try jTemplates or a simpler plugin



+1


source







All Articles