Twig检查文件是否存在

wob*_*ano 7 php file-exists twig

你好,所以我使用纤细的框架和树枝,这是我目前在PHP中的代码:

$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
Run Code Online (Sandbox Code Playgroud)

现在我想把if语句放在我的模板文件中.如何file_exists在我的树枝模板中使用该功能,以便检查文件是否存在?

Ano*_*ous 10

您可以创建自己的函数或测试,并将参数传递给PHP函数.

$test = new Twig_SimpleTest('ondisk', function ($file) {
    return file_exists($file);
});
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中:

{% if filename is ondisk %}
    blah
{% endif %}
Run Code Online (Sandbox Code Playgroud)

不幸的,英语听起来很奇怪.也许一个功能会更有意义.

  • 我应该把创建的函数放在哪里? (2认同)

via*_*nes 7

如果确实需要在模板端进行验证,则创建自定义函数就很好。但是Twig并不是要那样使用。

您可以只使valitadion php面并将标志传递给模板:

的PHP

$filename = '/path/to/foo.txt';
$file_exists = file_exists($filename);
// ...
$app->render(
    'yourTemplate',
    array( 'file_exists' => $file_exists )
);
Run Code Online (Sandbox Code Playgroud)

枝条

{% if file_exists %}
    do stuff
{% endif %}
Run Code Online (Sandbox Code Playgroud)

免责声明:我不知道使用Slim(此处为Symfony2的家伙)渲染树枝模板的确切方法,但这是相同的逻辑。