私はある種のマクロオートロードを実装しようとしています。インポートされたマクロが動作しない
アイデアは、マクロの束を定義し、次のすべてのテンプレートファイルで使用することです。ここで
は、私はそれをやろうとしている方法は次のとおりです。
<?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('@\[email protected]', $_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 %}
{{ macros_clearfix.clearfix(index=2, columns=6) }}
しかし、何も表示されます。210その後は、index.twig
の内側に、私はこれを持っています。
ただし、次のコードは動作します:私はおそらく間違って何をしていることができ
{% 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)}}' – DarkBee
私は知っていますが、どちらもまったく同じです。 (正直なところ)マクロの名前はゴミだから、私はそのように渡しています。だから私は何を意味するのか、マクロを読まずに知ることができます。 –
なぜこのような複雑なマクロシステムを使用していますが、これを行うにはtwig関数を追加するだけですか?マクロは、プロジェクトでグローバルに使用するためのものではありません。 Twig関数はコンテンツ生成を行い、グローバルに登録されることを意味します – goto