gpt4 book ai didi

php - Symfony2 和 Twig - 检查 Assets 是否存在

转载 作者:行者123 更新时间:2023-12-01 23:10:53 25 4
gpt4 key购买 nike

我有一个使用 twig 模板的 symfony2 项目。

我正在显示一些图像,并且希望仅在特定 Assets 存在时才显示图像。

我有这个:

{% if asset('bundles/sciforumversion2/images/logos/'~conf.img) %}
<img style="width: 60px; float:right; margin-right: 15px;" src="{{ asset('bundles/sciforumversion2/images/logos/')}}{{ conf.img }}"/>
{% endif %}

但是 if 条件总是为真。

有什么想法吗?谢谢。

最佳答案

如果你想检查一个 Assets 是否存在,你可以创建一个Twig extension实现功能。

PHP 在您的 Twig\Extension 目录中,使用以下内容创建 AssetExistsExtension.php:

<?php

namespace Fuz\TestBundle\Twig\Extension;

use Symfony\Component\HttpKernel\KernelInterface;

class AssetExistsExtension extends \Twig_Extension
{

private $kernel;

public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}

public function getFunctions()
{
return array(
'asset_exists' => new \Twig_Function_Method($this, 'asset_exists'),
);
}

public function asset_exists($path)
{
$webRoot = realpath($this->kernel->getRootDir() . '/../web/');
$toCheck = realpath($webRoot . $path);

// check if the file exists
if (!is_file($toCheck))
{
return false;
}

// check if file is well contained in web/ directory (prevents ../ in paths)
if (strncmp($webRoot, $toCheck, strlen($webRoot)) !== 0)
{
return false;
}

return true;
}

public function getName()
{
return 'asset_exists';
}

}

YML 这里是配置,放在你的 services.yml 文件中。

parameters:
(...)
fuz_tools.twig.asset_exists_extension.class: Fuz\TestBundle\Twig\Extension\Asset@ExistsExtension

services:
(...)
fuz_tools.twig.asset_exists_extension:
class: '%fuz_tools.twig.asset_exists_extension.class%'
arguments: ['@kernel']
tags:
- { name: twig.extension }

Twig 要在 twig 文件上使用此扩展,请使用:

{% if asset_exists('bundles/fuztest/images/test.png') %}

注意:不要忘记替换 namespace 以匹配您的项目。

关于php - Symfony2 和 Twig - 检查 Assets 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16898628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com