What are the real advantages of templating engines over just using PHP?

前端 未结 10 1642
青春惊慌失措
青春惊慌失措 2021-02-05 02:33

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

10条回答
  •  执念已碎
    2021-02-05 03:34

    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 %}
    

    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 template

    
    
    
    
      {% block head %}
        
        {% block title %}{% endblock %} - My Webpage
      {% endblock %}
    
    
      
    {% block content %}{% endblock %}

    child.html template

    {% extends "base.html" %}
    
    {% block title %}Index{% endblock %}
    {% block head %}
      {% parent %}
      
    {% endblock %}
    {% block content %}
      

    Index

    Welcome on my awesome homepage.

    {% endblock %}

    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.

    I recommend you give Twig a go. Extremely useful.

提交回复
热议问题