简体   繁体   English

PHP + JS的模板引擎,但是

[英]Template engine for PHP + JS but

I'm building a web app that relies fairly heavily on Ajax for its interactivity, and I want to get around the problem of having two versions of my HTML templates, to keep things DRY. 我正在构建一个Web应用程序,该Web应用程序在很大程度上依赖于Ajax的交互性,并且我想解决拥有两个版本的HTML模板的问题,以保持干燥。

I came across a question here, template engine both for JS and PHP , which came up with a good answer, mustache . 我在这里遇到了一个问题,即JS和PHP的模板引擎,都提出了一个很好的答案, Then I remembered all the stuff I wouldn't be able to do, like Zend_View_Helpers, and other PHP reliant stuff. 然后,我想起了所有我无法做的事情,例如Zend_View_Helpers,以及其他依赖PHP的东西。

My question is, are there any better solutions? 我的问题是,有没有更好的解决方案? Perhaps that would allow me to use Zend_View (or similar to output to a templating language), which would allow me the flexibility of PHP and its libraries, but the DRYness of a template language. 也许那将允许我使用Zend_View(或类似于输出到模板语言),这将使我具有PHP及其库的灵活性,但具有模板语言的DRYness。

That, or another solution entirely that I haven't thought of. 那,或者我完全没有想到的另一种解决方案。 I'm sure this sort of thing has been done many times before, so are there any best practices (or bad ones). 我确信这种事情以前已经做过很多次了,所以有没有最佳实践(或不好的实践)。

Thanks 谢谢

Whilst I am not entirely sure what you are attempting to do how about using the Twig project . 虽然我不确定您要使用Twig项目该如何做。 You can pass objects into the template and access its properties and methods: 您可以将对象传递到模板中并访问其属性和方法:

For convenience sake foo.bar does the following things on the PHP layer: 为了方便起见,foo.bar在PHP层上执行以下操作:

  • check if foo is an array and bar a valid element; 检查foo是否为数组并禁止有效元素;
  • if not, and if foo is an object, check that bar is a valid property; 如果不是,并且如果foo是对象,则检查bar是有效的属性;
  • if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead); 如果不是,并且如果foo是一个对象,则检查bar是有效的方法(即使bar是构造函数-改用__construct());
  • if not, and if foo is an object, check that getBar is a valid method; 如果不是,并且如果foo是对象,则检查getBar是有效方法;
  • if not, and if foo is an object, check that isBar is a valid method; 如果不是,并且如果foo是对象,则检查isBar是有效方法;
  • if not, return a null value. 如果不是,则返回一个空值。

foo['bar'] on the other hand only works with PHP arrays: 另一方面,foo ['bar']仅适用于PHP数组:

  • check if foo is an array and bar a valid element; 检查foo是否为数组并禁止有效元素;
  • if not, return a null value. 如果不是,则返回一个空值。

There is also a JS port of the Twig templating language . Twig模板语言还有一个JS端口

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

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