0

I am looking for a simple function or library that is very small and lightweight that will simply allow me to define a template which has placeholders that are populated from a JSON data result like the one below.

Most JavaScript template libraries I saw require you to define the template HTML inside of the page HTML either in a hidden DIV or inside <script> tags...

<script id="template" type="x-tmpl-mustache">
<div>
    <ul>
      <li>{{first_name}} {{last_name}} goes by the username of: {{user_name}}</li>
    </ul>
</div>
</script>

I need to be able to define the template HTML as a JavaScript string instead of like the above method...


var templateString = '<div>'+
'<ul>'+
'  <li>{{first_name}} {{last_name}} goes by the username of: {{user_name}}</li>'+
'</ul>'+
'</div>';

And then pass it some JSON like below and have it parse it to an HTML string which I can then manually inject into my DOM.

Can this be done without a fancy library? If I need a library, any suggestion for one that will work in the manner described above? As mentioned most that I saw require the template to be defined outside of JavaScript.

JSON DATA

{  
    "1":{  
        "id":"1",
        "user_name":"jasondavis",
        "first_name":"Jason",
        "last_name":"Davis",
        "is_admin":"1",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/31b64e4876d603ce78e04102c67d6144?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/31b64e4876d603ce78e04102c67d6144?s=80&d=identicon&r=PG"
    },
    "1702c3d0-df12-2d1b-d964-521becb5e3ad":{  
        "id":"1702c3d0-df12-2d1b-d964-521becb5e3ad",
        "user_name":"Jeff",
        "first_name":"Jeff",
        "last_name":"Mosley",
        "is_admin":"1",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/5359bf585d11c5c35602f9bf5e66fa5e?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/5359bf585d11c5c35602f9bf5e66fa5e?s=80&d=identicon&r=PG"
    },
    "1d77045b-fb16-d925-b19e-52c85d82bf81":{  
        "id":"1d77045b-fb16-d925-b19e-52c85d82bf81",
        "user_name":"PortalUser",
        "first_name":"Portal",
        "last_name":"User",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/0be68519dd27dc4586ad2246e7c1c2d6?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/0be68519dd27dc4586ad2246e7c1c2d6?s=80&d=identicon&r=PG"
    },
    "4bc81f9c-992f-ed11-5c64-558f5de81a87":{  
        "id":"4bc81f9c-992f-ed11-5c64-558f5de81a87",
        "user_name":"testtest",
        "first_name":"test",
        "last_name":"test",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/309bdb7b06aeb214c4fe6963e64de168?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/309bdb7b06aeb214c4fe6963e64de168?s=80&d=identicon&r=PG"
    },
    "6ce98c71-80c8-8b04-1767-52ccdd1b7c96":{  
        "id":"6ce98c71-80c8-8b04-1767-52ccdd1b7c96",
        "user_name":"TestUser",
        "first_name":"John",
        "last_name":"Doe",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/309bdb7b06aeb214c4fe6963e64de168?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/309bdb7b06aeb214c4fe6963e64de168?s=80&d=identicon&r=PG"
    },
    "95803cf3-84ea-493a-a030-52b0abcd9b0c":{  
        "id":"95803cf3-84ea-493a-a030-52b0abcd9b0c",
        "user_name":"test",
        "first_name":"test",
        "last_name":"test",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/309bdb7b06aeb214c4fe6963e64de168?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/309bdb7b06aeb214c4fe6963e64de168?s=80&d=identicon&r=PG"
    },
    "seed_chris_id":{  
        "id":"seed_chris_id",
        "user_name":"chris",
        "first_name":"Chris",
        "last_name":"Olliver",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/9655f78d38f380d17931f8dd9a227b9f?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/9655f78d38f380d17931f8dd9a227b9f?s=80&d=identicon&r=PG"
    },
    "seed_jim_id":{  
        "id":"seed_jim_id",
        "user_name":"jim",
        "first_name":"Jim",
        "last_name":"Brennan",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/db40f846ab0a3b10522f83c6ae657e31?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/db40f846ab0a3b10522f83c6ae657e31?s=80&d=identicon&r=PG"
    },
    "seed_max_id":{  
        "id":"seed_max_id",
        "user_name":"max",
        "first_name":"Max",
        "last_name":"Jensen",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/e4f7cd8905e896b04425b1d08411e9fb?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/e4f7cd8905e896b04425b1d08411e9fb?s=80&d=identicon&r=PG"
    },
    "seed_sally_id":{  
        "id":"seed_sally_id",
        "user_name":"sally",
        "first_name":"Sally",
        "last_name":"Bronsen",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/62bc326ac7fca09505ad10b8b1e0d9c5?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/62bc326ac7fca09505ad10b8b1e0d9c5?s=80&d=identicon&r=PG"
    },
    "seed_sarah_id":{  
        "id":"seed_sarah_id",
        "user_name":"sarah",
        "first_name":"Sarah",
        "last_name":"Smith",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/62a9731a313984d2576cd2b5528c0725?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/62a9731a313984d2576cd2b5528c0725?s=80&d=identicon&r=PG"
    },
    "seed_will_id":{  
        "id":"seed_will_id",
        "user_name":"will",
        "first_name":"Will",
        "last_name":"Westin",
        "is_admin":"0",
        "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/6976b4087070908d7c4c12ef3fc21d8b?s=80&d=identicon&r=PG",
        "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/6976b4087070908d7c4c12ef3fc21d8b?s=80&d=identicon&r=PG"
    }
}

2 Answers 2

1

html => JS

combine html template files into one JS file

template using templateString

var templateString = "<div><ul><li>{{first_name}} {{last_name}} goes by the username of: {user_name}}</li> </ul></div>";
var compiled = _.template(templateString);
compiled({ 'first_name': 'foo', last_name: "bar", user_name: "foobar" });
// → '"<div><ul><li>foo bar goes by the username of: foobar</li> </ul></div>"'

underscore/lodash (if you are already these libraries)

https://lodash.com/docs#template

// using custom template delimiters
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g; // changing to use {{}}
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// → 'hello mustache!'

mustache

https://github.com/janl/mustache.js

JS

function loadUser() {
  var template = $('#template').html();
  Mustache.parse(template);   // optional, speeds up future uses
  var rendered = Mustache.render(template, {name: "Luke"});
  $('#target').html(rendered);
}

HTML

<html>
<body onload="loadUser">
<div id="target">Loading...</div>
<script id="template" type="x-tmpl-mustache">
Hello {{ name }}!
</script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

21 Comments

THis is similar to my goal except the tempalate that is stored in the DOM script tags I am hoping to instead store inside a JS variable. DO you know if that is possibble....pretend I dont have access to the page and only am loading my JS file to the page
are you storing your template in script tags or are you asking if it's possilble to store it in JS vars?
I am wanting to store my templates as a JS variable in my JS project. So it would not be in script tags or in the DOM at all but instead contained within my JS FIle
Are you asking how to store it in JS or not to read templates from JS?
I want my template to be in a JS variable... var templateString = '<div>{{placeholder}}</div>';
|
0

Updating for ES6+ without any frameworks you'd do something like this:

const userHtml = (user) => { return `
    <div>
        <ul>
            <li>${user.first_name} ${user.last_name} goes by the username of: ${user.user_name}</li>
        </ul>
    </div>`;
}

const writeUsers = (articles) => {
    //where the html in the template goes
    const userListContainer = document.getElementById("userlist");

    users.forEach(user => {
        userListContainer.innerHTML += userHtml(user);
    });

}

fetch(datasrc)
    .then(response => response.json())
    .then(json => writeUsers(json));

You might have to adjust this a little based on your JSON format. You might also check out the <template> element if you are interested in a more HTML-centric approach.

1 Comment

Note: I didn't mention any "modern" framework solution since really unless you have a massive site that needs an enterprise framework like Angular, React, UI5, etc then you probably don't need to use one at all. They are almost entirely obsolete now, and as such contribute to unnecessary bloat.

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.