DEV Community

loading...

Using sprintf.js to make pure javascript templating

luciunknown profile image Luciano Cardoso ãƒŧUpdated on ãƒŧ2 min read

If you are dealing with only js project with no front-end framework, you may have noticed that some code blocks can be very repeated as long project grows. A commom example is html that holds information of a item in some list:

const persons = [
    {id:1, name:'Ted'},
    {id:2, name:'Bob'},
    {id:3, name:'Bar'},
    {id:4, name:'Foo'},
]

persons.forEach(function(person, index){
    let item = "<h3><a>"+person.id+"</a> "+person.name+"</h3>";
    document.body.innerHTML+= item;
});
Enter fullscreen mode Exit fullscreen mode

So we can change this previous example adding a simple template that grab most common HTML lists items like this:

const Template = {
    getPersonListItem:function(person){
         return "<h3><a>"+person.id+"</a> "+person.name+"</h3>";
    }
}
Enter fullscreen mode Exit fullscreen mode

we end up have something a little bit better than initial code:

const persons = [
    {id:1,name:'Ted'},
    {id:1,name:'Bob'},
    {id:1,name:'Bar'},
    {id:1,name:'Foo'},
]
const Template = {
    getPersonListItem:function(person){
         return "<h3><a>"+person.id+"</a> "+person.name+"</h3>";
    }
}

persons.forEach(function(person, index){
    let item = Template.getPersonListItem(person);
    document.body.innerHTML+= item;
});
Enter fullscreen mode Exit fullscreen mode

But we still have this string interpolation on "getPersonListItem" function. Thats when the sprintf js library can help to make this code more clean and readable. Keep in mind that this is a very simple example, but we know that HTML that represents a list item can be a lot more complex and sometimes a little tricky to maintain. So lets use sprintf.js :

const persons = [
    {id:1,name:'Ted', alias:'T'},
    {id:1,name:'Bob', alias:'B'},
    {id:1,name:'Bar', alias:'BA'},
    {id:1,name:'Foo', alias:'F'},
]
const Template = {
    personListItem:"<h3><a>%(id)i</a> %(name)s</h3>",
    personEspecialListItem:"<h5>%(alias)s</h5>"
}

persons.forEach(function(person, index){
    let item = sprintf(Template.personListItem, person);
    let title = sprintf(Template.personEspecialListItem, person);
    document.body.innerHTML+= item;
    document.body.innerHTML+= title;
});

Enter fullscreen mode Exit fullscreen mode

Now we have no string interpolation and we can pass person object directly to sprintf function, this allow us to write more complex templates and maintain on a single place all html related to a item.

Discussion (0)

pic
Editor guide