如何使用 Twig 创建扩展 [英] How to create an extension using Twig

查看:29
本文介绍了如何使用 Twig 创建扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Ubuntu 17.04 上运行 apache 和 php我正在使用树枝.我是这样安装 Twig 的.

I am running apache and php on Ubuntu 17.04 I am using twig. I installed Twig like this.

cd /var/www/html/my-new-website
composer install twig/twig
composer require twig/twig

此时我一直使用 Twig 的方式是:首先我创建一个 php 文件并做一些事情,创建一个数组并使用数组数据渲染模板.接下来,我将页面的各个部分分开并将它们放入模板中.

At this point the way I have been using Twig is: first I create a php file and do some stuff, create an array and render the template with the array data. Next I have separated sections of my page and put them in templates.

这是一个 index.php 示例,它创建一个目录数组,然后使用位于模板目录中的 files.html.twig 呈现它.

here is an example index.php that creates an array of directories then renders it with the files.html.twig located in the templates directory.

<?php
require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
    'cache' => 'cache',
));

$dir = "path/to/dir";
$exclude = array( ".","..",".*","index.php" );
$files = array_diff(scandir($dir), $exclude);

/*
echo ''; print_r($files);
*/

$template = $twig->loadTemplate('files.html.twig');
echo $template->render(['files' => $files]);
?>

这里是files.html.twig,它扩展了base.html.twig"

here is the files.html.twig, it extends "base.html.twig"

{% extends "base.html.twig" %}

{% block title %}
My Directory Listing
{% endblock %}

{% block content %}
    {% for file in files %}
      <li><a href="{{ file | url_encode }}">{{ file }}</a></li>
    {% endfor %}
{% endblock %}

并且 base.html.twig 包含带有导航栏和页脚的主要包装器.这一切都按预期工作.

and the base.html.twig contains main wrapper with navbar and footer. This all works as expected.

现在我的 base.html.twig 中有导航栏,它只是 html,我必须在其中编辑项目.

Right now I have the navbar in my base.html.twig, it is just html where I have to edit the items.

我已经创建了一个 php 函数来获取在模板(navbar.html.twig)中工作的导航栏数组,但问题是我必须在我创建的每个页面中放置或包含这个 php 函数.我希望我的 navbar.html.twig 模板直接从 php 函数中获取数组.

I have made a php function to get the navbar array that works in a template(navbar.html.twig), but the problem is I have to put or include this php function in each page I create. I want my navbar.html.twig template to get the array from the php funtion directly.

我相信我需要创建一个树枝扩展(php函数)并注册它.我已经阅读了关于此的文档(似乎都是为了完整的 symfony 安装,我只使用 twig).

I believe I need to create a twig extension(php function) and register it. I have read the docs on this(all seem to be for a full symfony install, I am using twig only).

我认为这篇文章走在正确的道路上,但没有提供我理解所需的信息 从 Twig 模板调用 PHP 函数

I think this article is on the right path but did not give me the information I needed to understand Call PHP function from Twig template

我不明白

  1. 在哪里放置我的 php 函数?我可以创建一个名为 extensions 的文件夹并在其中放置一个 navbar-list-funtion.php 文件吗?
  2. 在哪里注册函数以便它可以从模板中调用?一些文档说要在 app/config/services.yml 中注册(我没有这个文件或目录)
  3. 在我将 php 函数放在一个可识别的位置后,然后正确注册它,...我将如何在模板 navbar.html.twig 中调用返回的数组?

推荐答案

来自评论

如果你没有使用像 symfony 这样的框架,那么根据你如何处理这种情况,它有点味道.我,我自己,我在我的项目中使用命名空间来启用 Composer 的自动加载.我的树结构只是遵循我的命名空间,例如我的/项目/Twig/扩展

If you are not using a framework like symfony, it's a bit flavor based on how you deal with this situation. Me, myself, i'm using namespaces in my project to enable autoloading with composer. My tree structure just follows my namespace e.g. My/Project/Twig/Extensions

扩展 Twig 的最佳"方式是使用 Twig_Extension 类只需在您创建的文件夹中放置一个具有适当名称的新文件

The "best" way to extend Twig is by using a Twig_Extension class Just place a new file in the folders you created with an appropriate name

注意:从 Twig 2.X 开始,函数 getName() 不再是强制性的

note: As off Twig 2.X the function getName() is no longer mandator

我的/项目/Twig/Extensions/ProjectTwigExtension.twig

namespace My/Project/Twig/Extensions

class ProjectTwigExtension extends Twig_Extension {

    public function getFunctions() {
        return array(
            new Twig_SimpleFunction('twig_function_name', array($this, 'getTwigFunctionName')),
            new Twig_SimpleFunction('twig_function_foo', array($this, 'getTwigFunctionFoo')),
            //and so on....,            
        );  
    }

    public function getFilters() {
        return array(
            new Twig_SimpleFilter('twig_filter_name' , array($this, 'getTwigFilterName')),
            new Twig_SimpleFilter('twig_filter_foo' , array($this, 'getTwigFilterFoo')),
            //and so on....,
        );
    }

    public function getName() {
        return 'ProjectTwigExtension'; //this is mandatory for twig < 2.0
    }        
}

通过使用扩展类,您可以轻松地对所有函数/过滤器/节点/全局变量/...进行分组...创建此类后,您需要做的就是在 Twig 中注册该类.由于我不知道具体细节,因此您需要查看您的项目

By using an extension class you can easily group all your functions/filters/nodes/globals/... After you created this class all you need to do is register the class inside Twig. As I don't know the specifics you will need to look in your project where you do

$twig = new Twig_Environment($loader);

要注册该类,只需使用以下行,

To register the class just use the following line,

$twig->addExtension(new ProjectTwigExtension());

因为你可以扩展类有一个函数getFunctions,在这里你可以定义你想要的所有函数.

As you can the extension class has a function getFunctions, here you can define all the functions you want.

new Twig_SimpleFunction('twig_function_name', $callable)

第一个参数定义了如何在树枝模板中调用该函数,第二个参数是一个 可调用

The first argument defines how the function will be called inside a twig template, the second argument is a callable

  • new Twig_SimpleFunction('twig_function_name', array($this, 'method'))
    将调用当前扩展类内部的函数method
  • new Twig_SimpleFunction('twig_function_name', 'trim')
    会调用全局函数trim
  • new Twig_SimpleFunction('twig_function_name', array($obj, 'method'))
    将调用实例$obj
  • 的函数method
  • new Twig_SimpleFunction('twig_function_name', array('MyClass', 'method'))
    将从MyClass
  • 调用静态函数method
  • new Twig_SimpleFunction('twig_function_name', function($arg1, $arg2) {//...; })
    将执行关闭

这篇关于如何使用 Twig 创建扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆