template engine javascript and php/html
Recently I became interested of the jQuery template engine.
For the ajax call is very performant, because the data exchange is less.
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? One for php html and one for javascrip开发者_运维百科t?
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. 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. 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.
Here's an example. The json_encode function should be useful for this.
<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.
Your HTML page serves as part of the template.
<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".
精彩评论