简体   繁体   中英

Handlebars.js and multiple templates

I have a scenario in which I am receiving a json formatted array of objects from the server and I need to load varying handlebars templates based on the content type of the object being passed back. For example, my site is made up of multiple blocks of content and those blocks vary in the way in which they are displayed. So I will have one block that is one width and contains different content than another block which may be a different width and contains an entirely different kind of content that needs to be styled in a different way. I would like to use handlebars so that I am not building out a whole bunch of html with js and then inserting it into the DOM. Any ideas?

Assuming you don't have control over the response coming from the server, on page load, you could precompile your templates into a javascript object, keyed by the heuristic you are using to determine the appropriate template to use for the JS object. Then use that mapping to render the template when you receive your data.

How you preload this template mapping and do the rendering depends on what JS libs you are using (if any).

If you provide more details of your templates, the data, and environment some code might be able to be provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM