【问题标题】:Best practices to create a Twig HTML Layout (Masterpage)创建 Twig HTML 布局的最佳实践(母版页)
【发布时间】:2016-03-31 07:58:53
【问题描述】:

我已经开发C#/ASP.net MVC-App 5 年了,我现在正在学习PHP

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

 <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 作为参数调用树枝加载函数。最后,我必须为控制器创建 2 个视图(child.twig + index.php)和一个 php 文件。所以我的问题是:

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

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

提前致谢。

【问题讨论】:

  • 看看knpUniversities twig 教程(这个是免费的)。你需要的一切都应该在那里。
  • 谢谢我去看看

标签: php html twig


【解决方案1】:

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

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

【讨论】:

  • 谢谢米格尔。但是你仍然需要在一个额外的 php 文件中调用 oneChild.html 对吗?所以在 index.php 中:$template->display() / echo twig.render()。但我只想要一个新视图的一页让我们说 oneChild.html。
  • 没有。在您的 .php 中,您将我写在响应中。
猜你喜欢
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
  • 2016-01-02
相关资源
最近更新 更多