创建Twig HTML布局(母版页)的最佳实践


Best practices to create a Twig HTML Layout (Masterpage)

我已经开发C#/ASP.net MVC应用程序5年了,现在正在学习PHP

C#中,我可以为每个新站点使用RenderBody,因此新的HTML内容将在RenderBody()中被替换。然后,我只有一个新的局部视图和每个站点的一个新控制器:

 <html>
  <head>
    <title></title>
  </head>
  <body>RenderBody()</body>
</html>

当使用Twig时,我有一个骨架布局:

<html>
  <head>
    <title></title>
  </head>
  <body>{%block ablock%}{%endblock%}</body>
</html>

对于每个新站点,我需要制作一个新的child.twig文件并扩展主布局,然后覆盖"ablock"。通过这种方式,我仍然需要一个PHP文件(让我们称它们为index1.phpindex2.php等),它调用以child.twig为参数的trick加载函数。最后,我必须为控制器创建两个视图(child.twig+index.php)和一个php文件。所以我的问题是:

使用Twig在MVC中创建HTML主页的最佳方法是什么

我找不到任何公共项目/教程提及实现这一点的最佳实践。

提前谢谢。

我总是用共享所有页面的内容创建一个通用模板:

generalTemplate.html

<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="utf-8">
    <title>{{ page_title }}</title>
    <meta name="Author">
    <link rel="shortcut icon" href="{{project_path}}resources/images/favicon.ico">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Here put the general CSS and JS -->
    {% block head %} {% endblock %}
  </head>
  <body>
    <header>
    </header>
    {% block content %}{% endblock %}
    <footer>
    </footer>
  </body>
</html>

然后创建继承通用模板的子模板:

oneChild.html

{% extends "generalTemplate.html" %}
{% block head %}
<!-- Specific libraries css and js -->
{% endblock %}
{% block content %}
<!-- Specific HTML content -->
{% endblock %}

index.php

require_once 'Twig/Autoloader.php'; 
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem(path_to_generalTemplatehtml);
$twig = new Twig_Environment($loader, array());
$template = $twig->loadTemplate($path_to_oneChildhtml);
$data = array();
$data['project_title'] = $project_title;
$data['project_path'] = $project_path;
echo $template->render($data);

无论如何,Twig上有一个非常详细的文档:http://twig.sensiolabs.org/documentation