how to use dustjs-linkedin as client side templating?

前端 未结 2 433
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 03:28

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:<

相关标签:
2条回答
  • 2020-12-16 04:03

    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)

    0 讨论(0)
  • 2020-12-16 04:04

    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.

    0 讨论(0)
提交回复
热议问题