How to stock my Mustache / Handlebars templates in separate files?
Solution 1
I created and open-sourced NodeInterval for this exact same problem of too many js templates in my HTML page.
It allows you to put all your templates into a templates folder organized in whatever hierarchy you like. It has a built in watch
capability so that as you modify any of these templates it automatically updates your HTML page. I use it alongside SASS for my CSS.
I use it daily with underscore templates but it should work fine with moustache templates as well:
https://github.com/krunkosaurus/NodeInterval
Solution 2
Couldn't you just include a js file with your templates as js variables? Not tested, just thinking here:
//in your html page
<script id="avatar_tpl" type="text/html" src="mytemplates.js"></script>
// then in your mytemplates.js file
var template_1 = "{{ content }}";
var template_2 = "{{ content }}";
// and you could use it like this back in html page
var template1 = Handlebars.compile(template_1);
var template2 = Handlebars.compile(template_2);
Solution 3
if you are using jquery, you could create an invisible div with id "template-holder"
then use :
$("#template-holder").load([url here])
to load the html into the div then use :
var templatestr = $("#template-holder").find("#avatar_tpl").html()
to get the template
:)
Solution 4
I'm not familiar with handlebars.js but, have you tried this?:
<script id="avatar_tpl" type="text/html" src="myscript.html"></script>
Solution 5
I've been rolling all my scripts and templates in to one big .js file for several projects now. I use a java-based build tool, ant, to concatenate and manage various processing scripts for my js.
The biggest problem with storing large templates in javascript variables is javascript's lack of multi-line strings. I deal with this by writing my files with a python-like triple-quote syntax:
var templateVariable = '''
<div>
<div></div>
</div>
'''
I then run this custom-syntax javascript file though the python script included below, which turns it in to legal javascript:
#!/usr/bin/env python
# encoding: utf-8
"""
untitled.py
Created by Morgan Packard on 2009-08-24.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
import sys
import os
def main():
f = open(sys.argv[1], 'r')
contents = f.read()
f.close
split = contents.split("'''")
print "split length: " + str(len(split))
processed = ""
for i in range(0, len(split)):
chunk = split[i]
if i % 2 == 1:
processedChunk = ""
for i,line in enumerate(chunk.split("\n")):
if i != 0:
processedChunk = processedChunk + "+ "
processedChunk = processedChunk + "\"" + line.strip().replace("\"", "\\\"").replace('\'', '\\\'') + "\"" + "\n"
chunk = processedChunk
processed = processed + chunk
f = open(sys.argv[1], 'w')
f.write(processed)
f.close()
if __name__ == '__main__':
main()
Working this way, I can code templates in more-or-less pure html, and deploy them, along with application code, inside a single .js file.
pradon
Updated on June 18, 2022Comments
-
pradon almost 2 years
I'm using handlebars.js on a project and I'm starting to have a fair amount of templates. For now they are stored in my main template app file, like this :
<script id="avatar_tpl" type="text/html"> bla bla bla {{var}} bla bla bla </script>
I'm wondering if there is a way to put them in a separate file like a .js file or something, to avoid stacking them up in my source code page.
I'm aware that there are several solutions to call theses templates via Ajax, but that seems to result in too much unnecessary requests for me.
Thank you
-
Saroj Yadav almost 12 years
-
-
pradon over 12 yearsWell that could work of course, but I'm looking for a way to "package" several templates into one file, to avoid unnecessary requests
-
pradon over 12 yearsI could yes but doing so I'm losing the ability to use single and double quotes easily in my templates. Also the automatic compilation of the templates are harder this way (right now I'm just looking for every text/html markup via jQuery and compile them on the fly at startup)
-
morgancodes over 12 yearsIf you want to try these and need help, let me know and I'll be glad to walk you through more specifics.
-
swatkins over 12 yearsWould you prefer to precompile your templates? Take a look at github.com/wycats/handlebars.js and scroll down to Precompiling Templates.
-
pradon over 12 yearsThank you very much morgan, maybe I'll do that yes =)
-
morgancodes over 12 yearsLooks like the handlebars precompile is probably a better way to go.
-
pradon over 12 yearsDude ! I use SASS everyday and I think I'm gonna love this if it work as advertised ^^ Is there any way that instead of html file you could input a js filem with pre-compiled js templates in it ? Thank you very much
-
Mauvis Ledford over 12 yearsmdcarter: The template files can be in any format as long as they have an id property somewhere in them. It sorts the templates alphabetically and then put them in your page. Check out the documentation on the above link, it explains everything fairly well, and if it doesn't, just let me know.
-
Daniel Buckmaster almost 12 yearsI'm looking for an approach like this, but the above doesn't seem to work for me. Chrome says
Resource interpreted as Script but transferred with MIME type text/html
-
Paco Valdez almost 12 yearsindeed doesn't work in chrome, maybe you can import a javascript string variable that contains your html and then assign a innerHTML to that string.
-
Yossi Shasho about 11 yearsThis is great, thanks! I only wish it could also precompile them.
-
Emissary over 10 yearsBut he/she's not using jQuery... the toolset is stipulated in the tags underneath the question. It's great that you want to help but try to stay on topic. There are plenty of jQuery specific questions on StackOverflow, imposing it elsewhere only serves to pollute the knowledge base.
-
Chris Dutrow about 8 years@Emissary: I don't think not including the jQuery tag means he is definitely not using it.
-
Emissary about 8 years@ChrisDutrow wow, old post... the question is in the public domain - it's not just about the original poster. jQuery is overused where it's often unnecessary and there are already thousands of similar questions on SO explicitly targeting jQ solutions. When folks feel the need to post a jQ solution to a non-jQ question, it just adds noise to the site / dilutes quality.
-
Chris Dutrow about 8 years@Emissary - For me its not about the original poster either. I believe that his answer was helpful and would like to see more answers like it.