如何在没有nodejs的PHP代码中编写dustjs

目前我在客户端javascript中执行了如下操作

      $(document).ready(function(){ // JSON response from server var json_object = { "profile_skill": "Profile Skill", "skills": [ { "name": "JavaScript" }, { "name": "Ruby" }, { "name": "Java" } ] } // render method dustRender = function(){ // Get the dust html template to dust compile var dust_tag = $('#page').html() ; var compiled = dust.compile(dust_tag, "tmp_skill"); //load templates dust.loadSource(compiled); //Renders the named template and calls callback on completion. context may be a plain object or an instance of dust.Context. dust.render("tmp_skill", json_object, function(err, html_out) { //HTML output $('#page').html(html_out); console.log(html_out); }); }(); });    

Dust templates in the browser

{profile_skill}
    {#skills}
  • {name}
  • {/skills}

但在我的页面查看源中,我可以看到上面的代码而不是html标记输出。 而且我想知道如何在php代码中集成dustjs。

正如Torsten Walter所提到的,如果您在浏览器中编译/渲染,则无法在页面中看到html源代码。 如果在服务器端进行编译和渲染,html源代码将包含最终的HTML代码。 为实现这一目标,您可以使用Linkedin博客中提到的nodejs或Rhino服务器: http ://engineering.linkedin.com/frontend/leaving-jsps-dust-moving-linkedin-dustjs-client-side-templates

这可能有助于您使用PHP编译灰尘模板,

https://github.com/saravmajestic/myphp/tree/master/dustcompiler

此实用程序仅用于在页面中呈现之前编译灰尘模板,这将避免在浏览器中编译时间。 您可以将编译后的模板作为JS文件加载到页面中,可以使用其他JS文件/模板进行缩小/聚合。

希望这可以帮助!!!

不要只是把你的模板放在PHP中。 正确执行并将模板定义为字符串或单独的html文件。

 var templateName = "myTemplate"; var model = { "profile_skill": "Profile Skill", "skills": [ { "name": "JavaScript" }, { "name": "Ruby" }, { "name": "Java" } ] }; dust.onLoad = function(templateName, callback) { // this will load a template with [name].html in the folder templates // callback is an internal dust.js function $.get(["templates/", ".html"].join(templateName), function(data) { callback(undefined, data); }, "html"); }; // dust just takes the template name as first parameter // if no template of this name is defined it will attempt to load // and compile it if needed // override dust's onLoad function to implement your loading dust.render(templateName, model, function(err, out){ $('#page').html(out); }); 

在我的template.html中

 {profile_skill} 
    {#skills}
  • {name}
  • {/skills}

当然,关键是编译模板总能加快交付和渲染速度。 但是,由于您将模板与页面的其余部分一起交付,因此不需要调用loadSourcecompile 。 相反,如果你告诉它,灰尘会试图自己加载一个临时状态。

从文档:

载入中

(……)

默认情况下,当命名模板无法位于缓存中时,Dust会返回“找不到模板”错误。 覆盖onLoad以指定回退加载机制(例如,从文件系统或数据库加载模板)。

如果必须,内部灰尘将调用loadSource并自行compile方法。 在我上面的例子中,我包含了一个可能的覆盖dust.onLoad来覆盖dust.onLoad 。 当然你也可以简单地返回一个DOM节点的html内容。

 dust.onLoad = function(templateName, callback) { callback(undefined, $("skill template").hmtml()); } 

并回答你的最后一个问题:

而且我想知道如何在php代码中集成dustjs。

你不能。 除非您将模板发送到客户端进行渲染,或者您的后端有一个JavaScript解释器来渲染模板,否则您无法使用它。

Interesting Posts