twig 时间函数_扩展Twig模板:继承,过滤器和函数

twig 时间函数

When working within an MVC architecture, it’s common to use a template library to populate the dynamic content of our views. There are dozens of such libraries available for PHP, but Twig is one of the standouts because of the ability to extend core features with custom implementations. In this article we’ll explore how Twig templates can be extended using template inheritance, filters, and functions.

在MVC架构中工作时,通常使用模板库来填充视图的动态内容。 有数十种此类库可用于PHP,但是Twig是其中的佼佼者,因为它能够通过自定义实现扩展核心功能。 在本文中,我们将探讨如何使用模板继承,过滤器和函数扩展Twig模板。

模板库的局限性 (Limitations in Template Libraries)

The most common limitation that many template libraries have is the inability to extend template features. For example, it’s common to include all of the references to CSS and JavaScript files in the header or footer section of a page, and so we create a header template and include that file in all of our pages. But what if we have a page which needs to initialize a Google map on page load? The JavaScript for the map should be only called from this one page, but many developers would needlessly include all of the JavaScript and CSS files in the one header.

许多模板库最普遍的限制是无法扩展模板功能。 例如,通常在页面的页眉或页脚部分中包含对CSS和JavaScript文件的所有引用,因此我们创建了一个标题模板并将该文件包含在我们的所有页面中。 但是,如果我们有一个页面需要在页面加载时初始化Google地图,该怎么办? 只能从这一页调用地图JavaScript,但是许多开发人员会不必要地将所有JavaScript和CSS文件都包含在一个标头中。

Another workaround is to include the common shared files in the header and include the other specific files inside the page templates as necessary. The header file might look like this:

另一个解决方法是在标题中包含公共共享文件,并在必要时在页面模板中包含其他特定文件。 头文件可能如下所示:

<!DOCTYPE html>
<html>
 <head>
  <link rel="stylesheet" href="style.css">
  <script src="jQuery.js" type="text/javascript"></script>
 </head>

… and the map template might look like this:

…,地图模板可能如下所示:

<script src="googlemaps.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#google_map").google_map();
});
</script>
<div id="google_map"></div>

The common CSS and JavaScript are referenced in the header, and map-specific code is inside the page template. While this works, ideally we should keep all of these references in one place for consistency and cleaner code instead of split across files like this.

标头中引用了常见CSS和JavaScript,页面模板中包含了特定于地图的代码。 在这种情况下,理想情况下,我们应该将所有这些引用都放在一个地方,以保持一致性和更简洁的代码,而不是像这样在文件中进行拆分。

With most template libraries, we have no option other than to go with the techniques above. But now let’s see what Twig offers to cope with this situation.

对于大多数模板库,除了采用上述技术外,我们别无选择。 但是,现在让我们看看Twig为应对这种情况提供了什么。

扩展树枝模板 (Extending Twig Templates)

Twig gives us the ability to extend child templates from parent templates using inheritance. Probably the easiest way to see how inheritance works is with an example. The following code is a parent template:

Twig使我们能够使用继承从父模板扩展子模板。 看继承如何工作的最简单方法可能就是一个示例。 以下代码是父模板:

<!DOCTYPE html>
<html>
 <head>
  {% block head %} Sample Content {% endblock %}
 </head>
 <body>
 </body>
</html>

We define blocks inside the parent template which have a name and some content inside it. Then we can extend the defined blocks inside child templates like so:

我们在父模板中定义了具有名称和一些内容的块。 然后,我们可以在子模板中扩展已定义的块,如下所示:

{% extends "parent.html" %}
{% block head %} Head 1 {% endblock %}

In the child, we extend the parent template by using the extend keyword followed by the template file name. We then redefine the head block to contain dynamically extended content. Omitting the head block in child template will cause the parent to use the content it already has defined as a default.

在子级中,我们通过使用extend关键字和模板文件名来扩展父级模板。 然后,我们重新定义head块以包含动态扩展的内容。 在子模板中省略head块将导致父模板使用其已经定义为默认值的内容。

Now that we have a basic idea of how inheritance works in Twig, let’s create a more complete page layout.

现在我们有了继承在Twig中如何工作的基本概念,让我们创建一个更完整的页面布局。

<!DOCTYPE html>
<html>
 <head>
  {% block head %}
  <link rel="stylesheet" href="style.css">
  <script src="jQuery.js" type="text/javascript"></script>
  {% endblock %}
 </head>
 <body>
  <div id="grid">{% block content %} {% endblock %}</div>
  <div id="info">{% block sidebar %} {% endblock %}</div>
  <div id="footer">
   {% block widget1 %} {% endblock %}
   {% block widget2 %} {% endblock %}
   {% block widget3 %} {% endblock %}
   {% block footer %}
   &copy; 2013 example.com
   {% endblock %}
  </div>
 </body>
</html>

I’ve created a main template which contains all of the components of a standard web page. There’s a header block where we can include files dynamically, a dynamic main content area, and an information sidebar. In the footer there’s three dynamic widgets followed by the copyright message.

我创建了一个主模板,其中包含标准网页的所有组件。 有一个标头块,我们可以在其中动态包含文件,动态主要内容区域和信息侧栏。 页脚中有三个动态小部件,其后是版权信息。

With other templating systems we might have to create headers, footers, content, and sidebars separately to reuse across multiple templates. But with Twig’s support of inheritance, we can create the one main template to use across all of the pages in our site.

使用其他模板系统,我们可能必须分别创建页眉,页脚,内容和侧边栏,以在多个模板之间重用。 但是,在Twig支持继承的情况下,我们可以创建一个主模板,以在我们网站的所有页面中使用。

Let’s say we want a use the template for a page which relies on a specific jQuery plugin. Basically we need to include the plugin’ files which depend on the jQuery library we’ve already provided, so we would extend the template this way:

假设我们要为依赖特定jQuery插件的页面使用模板。 基本上,我们需要包括依赖于我们已经提供的jQuery库的插件文件,因此我们将以这种方式扩展模板:

{% block head %}
{{ parent() }}
<script src="jquery.plugin.js"></script>
{% endblock %}

The head block is redefined to reference the custom plugin files, but also while preserving the contents of original head section. The parent() function is used to retrieve the original head content.

重新定义了head块以引用自定义插件文件,同时还保留了原始head部分的内容。 parent()函数用于检索原始标题内容。

Indeed, Twig templates are highly flexible and are able to cater any type of requirement. Blocks can be placed anywhere, and block content can be changed in various ways to suit our needs.

实际上,Twig模板具有很高的灵活性,并且能够满足任何类型的需求。 块可以放置在任何地方,并且块内容可以通过各种方式更改以满足我们的需求。

Up until now we’ve only discussed how we can use template inheritance to extend our templates. Twig comes with a number of features to further extend templates; let’s look now at how filters and functions fit into the process.

到目前为止,我们仅讨论了如何使用模板继承来扩展模板。 Twig具有许多功能来进一步扩展模板。 现在让我们看一下过滤器和函数如何适应流程。

树枝过滤器的作用 (Role of Twig Filters)

Filters are used to modify variables inside a template. You can find a list of built-in filters in the Twig documentation, but to illustrate the concept I’ll show you the basic usage of a filter to remove leading and trailing whitespace from a value.

过滤器用于修改模板中的变量。 您可以在Twig文档中找到内置过滤器列表 ,但是为了说明这一概念,我将向您展示过滤器从值中删除前导和尾随空格的基本用法。

{{ "Varible content" | trim() }}

Built in filters are very useful, but the real power of filters come with the implementation of custom filters. Twig provides a well-defined method for creating our own filters. Since data grids are a common means of presenting data in a web app, let’s assume we have a grid that displays a product table with different categories. We’ve been asked to display the data with each category highlighted with a specific color. We can use a custom filter to implement this feature.

内置过滤器非常有用,但是过滤器的真正功能在于自定义过滤器的实现。 Twig提供了定义明确的方法来创建我们自己的过滤器。 由于数据网格是在Web应用程序中显示数据的常用方法,因此我们假设我们有一个网格来显示具有不同类别的产品表。 我们被要求显示数据,每个类别用特定的颜色突出显示。 我们可以使用自定义过滤器来实现此功能。

New filters are created by using anonymous PHP functions and the Twig_SimpleFilter class.

通过使用匿名PHP函数和Twig_SimpleFilter类创建新的过滤器。

<?php
$filter = new Twig_SimpleFilter("highlight", function ($key) {
    switch (trim($key)) {
        case "book_category":
            echo '<span class="books_color">';
            break;
        case "cd_category":
            echo '<span class="cd_color">';
            break;
        case "ebook_category":
            echo '<span class="ebook_color">';
            break;
        default:
            // nothing
    }
});
$twig->addFilter($filter);

I’ve created a new filter named “highlight”, and then added it to the Twig environment using the addFilter() method. A category will passed to the filter as a variable, and inside the function we switch the category and output an element with specific CSS class to generate the dynamic highlighting in the grid.

我创建了一个名为“ highlight”的新过滤器,然后使用addFilter()方法将其添加到Twig环境中。 类别将作为变量传递到过滤器,在函数内部,我们切换类别并输出具有特定CSS类的元素以在网格中生成动态突出显示。

We can use this filter inside our templates like so, with products as an array which consists of our product names and categories:

我们可以像这样在产品模板中使用此过滤器,将产品作为包含我们产品名称和类别的数组:

{% block content %}
 {% for product in products %}
  <div>
   {% filter highlight %}
   {{ product.category }}
   {% endfilter %}
   {{ product.product }}
   </span>
  </div>
 {% endfor %}  
{% endblock %}

细枝功能的作用 (Role of Twig Functions)

Twig functions are used to add dynamic content to our templates. There’s a selection of built-in functions, but as with filters, the real power of function comes with the ability to create our own implementations.

Twig函数用于将动态内容添加到我们的模板中。 有很多内置函数可供选择 ,但是与过滤器一样,功能的真正强大之处在于能够创建我们自己的实现。

<?php
$function = new Twig_SimpleFunction("function_name", function ($arg1, $arg2) {
    // implementation
});
$twig->addFunction($function);

Again we can use anonymous functions to create dynamic Twig functions. The first parameter to the Twig_SimpleFunction class is the name of the function, and the second is the function definition. The function is added to the Twig environment using addFunction().

同样,我们可以使用匿名函数创建动态的Twig函数。 Twig_SimpleFunction类的第一个参数是函数的名称,第二个是函数定义。 使用addFunction()将函数添加到Twig环境中。

Let’s assume that we are using a library for working with form fields like textboxes, checkboxes, etc. Usually we just write the required HTML directly in the templates like so:

假设我们正在使用一个库来处理诸如文本框,复选框等表单字段。通常,我们只是直接在模板中编写所需HTML,如下所示:

<input type="text" name="fname" class="chosen">

But if the library requires certain attributes to work it can be difficult to include the necessary HTML for every form without making any mistakes. We can create a Twig function to insert each of the field instead.

但是,如果库要求某些属性才能起作用,则可能很难为每个表单包括必要HTML而不会犯任何错误。 我们可以创建一个Twig函数来代替插入每个字段。

<?php
$function = new Twig_SimpleFunction("form_text", function ($name, $id, $value = "", $class = "form_text") {
    echo '<input type="text" name="'.$name.'" id="'.$id.'" value="'.$value.'" class="'.$class.'">";
});
$twig->addFunction($function);

This technique makes sure that we include the correct attributes without making mistakes. We would call this function from within our templates using the following:

该技术确保我们包含正确的属性而不会出错。 我们将使用以下模板从模板中调用此函数:

{{ form_text("fname", "fname", "", "chosen") }}

Inheritance, filters, and functions are a powerful combination when it comes to extending Twig templates. We can use these in different ways to easily deal with the advanced requirements of our application.

在扩展Twig模板时,继承,过滤器和函数是强大的组合。 我们可以以不同的方式使用它们来轻松满足应用程序的高级要求。

摘要 (Summary)

The ability to create extensible templates allows us to reuse templates and features in multiple places throughout our applications when necessary, and Twig is one of best templating libraries when it comes to support for for extending the core library’s functionality. Twig also comes with extensive documentation explaining every aspect of the template creation process, which makes extending things easy.

创建可扩展模板的能力使我们能够在必要时在整个应用程序中的多个位置重用模板和功能,并且在支持扩展核心库功能方面,Twig是最佳模板库之一。 Twig还​​附带了大量文档,解释了模板创建过程的各个方面,使扩展工作变得容易。

Let me know your experiences with Twig and your thoughts on its template extending process. I’m looking forward to hearing from you.

让我知道您对Twig的经验以及对模板扩展过程的想法。 期待收到你的消息。

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/extending-twig-templates-inheritance-filters-and-functions/

twig 时间函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值