【发布时间】:2017-05-21 03:57:51
【问题描述】:
我正在尝试实现某种宏自动加载。
这个想法是定义一堆宏并在所有下一个模板文件中使用它们。
这是我的尝试:
<?php
define('ROOT_FRONT', '/path/to/files/');
define('LAYOUT_DIR', ROOT_FRONT . 'layout/');
include(ROOT_FRONT . 'lib/Twig/Autoloader.php');
Twig_Autoloader::register();
$twig_loader = new Twig_Loader_Filesystem(array(LAYOUT_DIR, ROOT_FRONT));
$twig = new Twig_Environment($twig_loader, array(
'charset' => 'ISO-8859-15',
'debug' => !!preg_match('@\.int$@', $_SERVER['SERVER_NAME']),
'cache' => $_SERVER['DOCUMENT_ROOT'] . '/cache/twig/'
));
$macro_code = '';
foreach(array_filter(
array_diff(
scandir(LAYOUT_DIR . 'macros/'),
array('..','.')
),
function($file)
{
return strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'twig'
&& is_file(LAYOUT_DIR . 'macros/' . $file);
}
) as $file)
{
$info = pathinfo($file);
$macro_code .= '{% import \'macros/' . $info['basename'] . '\' as macros_' . $info['filename'] . ' %}';
}
$twig
->createTemplate($macro_code)
->render(array());
$twig->display('index.twig', array());
如果我有一个文件,比如macro/clearfix.twig,它将在$macro_code 内部生成这个模板代码:
{% import 'macros/clearfix' as macros_clearfix %}
macro/clearfix.twig 里面的代码是这样的:
{% macro clearfix(index, columns) %}
{% if index is divisible by(columns) %}
<div class="clearfix visible-md-block visible-lg-block"></div>
{% endif %}
{% if index is even %}
<div class="clearfix visible-sm-block"></div>
{% endif %}
{% endmacro %}
然后,在index.twig 中,我有这个:
{{ macros_clearfix.clearfix(index=2, columns=6) }}
但是什么都没有显示。
但是,以下代码可以工作:
{% set index = 2 %}
{% set columns = 6 %}
{% if index is divisible by(columns) %}
<div class="clearfix visible-md-block visible-lg-block"></div>
{% endif %}
{% if index is even %}
<div class="clearfix visible-sm-block"></div>
{% endif %}
我可能做错了什么?
我是否误解了某些内容或应用不正确?
【问题讨论】:
-
你奇怪地传递了参数,你应该像这样传递它们:
{{ macros_clearfix.clearfix(2, 6) }} -
我知道,但两者的意思完全相同。由于(老实说)宏的名称是垃圾,我就这样传递它们。这样我就可以知道什么意思,不用看宏。
-
你为什么要使用这个复杂的宏系统,而你可以添加twig函数来做到这一点?宏并不意味着在项目中全局使用。 Twig 功能旨在进行内容生成并在全球范围内注册
-
@goto 我正在写一些基于此的东西。事实上,我正在为此写一个答案并展示一些代码。