简体   繁体   English

模板引擎javascript和php / html

[英]template engine javascript and php/html

Recently I became interested of the jQuery template engine. 最近,我对jQuery模板引擎产生了兴趣。

For the ajax call is very performant, because the data exchange is less. 对于ajax调用非常有表现力,因为数据交换较少。

But when I load my application the first time, I use only php and html for print the data, so for use this technic do I have to duplicate the template? 但是,当我第一次加载应用程序时,我仅使用php和html来打印数据,因此要使用该技术,我是否必须复制模板? One for php html and one for javascript? 一种用于php html,一种用于javascript?

How could I resolve this problem? 我该如何解决这个问题?

It is possible to use the same templates on the server side and the client. 可以在服务器端和客户端使用相同的模板。 For example, mustache has implementations in several languages including PHP and Javascript. 例如, 有几种语言的实现,包括PHP和Javascript。 But generally I find it's easier to stick to one approach. 但总的来说,我发现坚持一种方法更容易。

If you're using jQuery templating to render on the client anyway, why not render in Javascript the first time as well. 如果您仍然使用jQuery模板在客户端上进行渲染,那为什么不也第一次使用Javascript进行渲染。 To avoid needing an extra AJAX call, you can inject your data model into the page as a javascript object and pass that into the template renderer. 为避免额外的AJAX调用,您可以将数据模型作为javascript对象注入页面中,然后将其传递到模板渲染器中。

Here's an example. 这是一个例子。 The json_encode function should be useful for this. json_encode函数应该对此有用。

<script type="text/javascript">

// This line gets generated by your PHP code.
//   You'll want to use the JSON methods instead of generating it by hand.
var myModel = { name: 'Fred', surname: 'Bloggs' };

$(document).ready(function() {
    // Here you render the template using the data that's
    //   already in myModel
});

</script>

You could try Distal templating engine . 您可以尝试使用Distal模板引擎

Your HTML page serves as part of the template. 您的HTML页面是模板的一部分。

<div>
  Hi, <span data-qtext="user.name">Guest</span>
</div>

When you first load it displays "Hi, Guest" then you run the template and you can substitute for "Guest". 首次加载时,它会显示“ Hi,Guest”,然后运行模板,并可以替代“ Guest”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM