我已经开发 C#/ASP.net
MVC-App 5 年了,现在我正在学习 PHP
。
在 C#
中,我可以为每个新站点使用 RenderBody
,因此新的 HTML 内容将在 RenderBody()
中被替换。然后,每个站点只有一个新的局部 View 和一个新的 Controller :
<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.php
、index2.php
等),它使用 调用 twig 加载函数>child.twig
作为参数。最后,我必须为 Controller 创建 2 个 View (child.twig
+ index.php
)和一个 php 文件。所以我的问题是:
使用 Twig 在 MVC 中创建 HTML 母版页的最佳方法是什么?
我找不到任何提及执行此操作的最佳实践的公共(public)项目/教程。
提前致谢。
最佳答案
我总是使用共享所有页面的内容创建一个通用模板:
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>
然后创建继承通用模板的 child :
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
关于php - 创建 Twig HTML 布局(母版页)的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36327421/