与仅使用 PHP 相比,模板引擎的真正优势是什么? [英] What are the real advantages of templating engines over just using PHP?

查看:24
本文介绍了与仅使用 PHP 相比,模板引擎的真正优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只使用 PHP 作为视图文件来开发我的 Web 应用程序,我觉得没有任何限制,但我听说有一致数量的开发人员提倡外部"模板引擎.那么,模板引擎提供了哪些简单的 PHP 所缺乏的东西?

I develop my web applications using only PHP for the view files and I don't feel limited in any way, but I hear there's a consistent number of developers advocating "external" templating engines. So what do template engines offer that simple PHP lacks?

我正在寻找实用的东西,所以我排除了以下内容:

I'm looking for practical things, so I exclude the following:

  • 照顾糟糕的开发人员(即使用模板引擎,因为它迫使您不能将代码混合到演示文稿中)
  • 语法简洁(我在 Vim 中为 <?php echo $stuff; ?> 之类的东西进行了映射,使用花括号不会有任何区别)
  • 为非程序员提供更简单的语法(我独自开发所以这不是问题)
  • babysitting bad developers (i.e. use a template engine because it forces you to not mix code into presentation)
  • conciseness of syntax (I have mappings in Vim for things like <?php echo $stuff; ?>, using curly braces wouldn't make any difference)
  • easier syntax for non programmers (I develop alone so that's not an issue)

推荐答案

新语法

<小时>

有些人不会同意,但因为我一直在使用 Twig,所以for ... else"感觉是对的.它可能不是很多,但它使我的模板更简洁.

New Syntax


Some people wont agree, but since I've been using Twig the "for ... else" feels right. It might not be a lot, but it keeps my templates that little bit cleaner.

{% for row in articles %}
 Display articles ...
{% else %}
 No articles.
{% endfor %}

自动转义

<小时>

您可以让模板引擎自动转义任何输出.这很棒,因为您不再需要在任何地方重复 htmlspecialchars ....Twig 很好地做到了这一点.

Automatic Escaping


You can have the template engine automatically escape any output. This is great as you no longer have to repeat htmlspecialchars ... everywhere. Twig does this nicely.

{% autoescape on %}
  Everything will be automatically escaped in this block
{% endautoescape %}

模板继承

<小时>

我喜欢的另一个功能是扩展基本模板的能力.这是一个基本的例子

Template Inheritance


Another feature I like is the ability to extend base templates. Here's a basic example

base.html 模板

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  {% block head %}
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}{% endblock %} - My Webpage</title>
  {% endblock %}
</head>
<body>
  <div id="content">{% block content %}{% endblock %}</div>
  <div id="footer">
    {% block footer %}
      &copy; Copyright 2009 by <a href="http://domain.invalid/">you</a>.
    {% endblock %}
  </div>
</body>

child.html 模板

A child template can override blocks for page specific styles, content, etc ... You can also notice the use of {% parent %} which grabs the parents content so you don't lose it all while overriding.

子模板可以覆盖页面特定样式、内容等的块……您还可以注意到 {% parent %} 的使用,它会抓取父内容,因此您在覆盖时不会丢失所有内容.

我建议您尝试一下 Twig.非常有用.

I recommend you give Twig a go. Extremely useful.

这篇关于与仅使用 PHP 相比,模板引擎的真正优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆