pre-compile JavaScript templates to functions on project build

拜拜、爱过 提交于 2019-12-22 18:28:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!