how to use dustjs-linkedin as client side templating?

こ雲淡風輕ζ 提交于 2019-12-18 03:35:37

问题


I get the idea of server and client side templating, but dust.js confuses me a little bit.

In order to use dust.js for client side templating, you need three steps:

  1. complie the template
  2. load the template
  3. render the template

Right?

But where do the templates come from? I saw two different methods:

 1. <script> template <script>
 2. <div> template </div>

... Both of them are in the DOM. Which is correct?

I also notice that you can load the template via ajax, so the template won't be seen in the DOM, but I don't know how to do that.

Also, I'm currently using jade as express view engine. Is it necessary to switch to dust.js? What is the advantage?


回答1:


This is LinkedIn Dust JS wiki page that can answer your questions and has very good examples: http://linkedin.github.com/dustjs/

But to answer your questions here:

Yes you need to compile your dust template which becomes a JavaScript file that you can add to your page by <script> tag and then call dust.render method to render your template. Here is an example:

  1. write following code in a template file and save it as sample.tl

    <p>Hi {firstName} {lastName}</p>
    
  2. compile sample.tl to sample.js by dustc sample.tl in command line or use dust.compile("your_template_code", "template_name") to compile the template and save the output in a JavaScript file (sample.js) or you use duster.js to watch and compile templates by nodejs: https://github.com/dmix/dusterjs

  3. add sample.js in your html:

    <script type="text/javascript" src="sample.js"></script>
    

    this will also register your template to dust.cache.

  4. in your JavaScript:

    var your_json = {firstName:'James', lastName:'Smith'};
    
    dust.render('sample', your_json, function(err, out){
    
        your_dom_element.innerHTML = out;
    
    });
    

    The result of above dust.render method will be <p>Hi James Smith</p>

    So you need to pass 3 arguments to dust.render: dust.render(template_name, json, callback)




回答2:


As the wiki say, you can use dust in the client or in the server. If you use it in the client you should get the template (for example with an ajax request), compile it an render in the browser. You will have to include the dust scripts file in your page.

By the other hand you can use dust in the server, (using rhino or nodejs). In this case you are going to compile and render the template in the server so the browser will receive html.



来源:https://stackoverflow.com/questions/13736462/how-to-use-dustjs-linkedin-as-client-side-templating

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