问题
Update I want to avoid compiling the templates client-side, and have them compile during my local ant build process. Perhaps something like loading jQuery and jQuery templates into rhino, passing the $.template()
function the contents of each .jst file in turn, and building a "templates.js" which should contain:
$.template['model-view'] = resultingFunction.toString();
// 1 for each .jst file
This way, I can maintain each template in a seperate file, and avoid having all clients redundantly compile the same template.
I'm using jQuery templates, and was hoping to separate them out into their own files (eg. model-view.jst) that are compiled into functions when the project is built and made available in the jQuery .tmpl() scope for later use.
For example, given the file model-view.jst
<li>${name}</li>
This file and all other .jst files should be picked up on build, compiled into a function that can later be used anywhere in the program like so:
$.tmpl('model-view', {
name: 'Matt'
});
回答1:
I solved this problem using Node.js and coffeescript by making directory of partial templated into executable, pre-compiled functions. Hope this helps.
https://github.com/wookiehangover/jquery-tmpl-jst
回答2:
I let you decide if you like it or not :)
in you common js library define this function:
function loadTemplate(templateName) {
$.ajax({
url: templateName + '.jst',
success: function(data) {
$.template(templateName, data);
}});
}
Then in you master hml file <head></head>
section you can add:
<script type="text/javascript">loadTemplate('model-view');</script>
<script type="text/javascript">loadTemplate('another-model-view');</script>
so you can use anywhere in your code
$.tmpl('model-view', your-data)
$.tmpl('another-model-view', your-data)
Hope it helps
来源:https://stackoverflow.com/questions/6464933/pre-compile-javascript-templates-to-functions-on-project-build