[英]Symfony2 and Twig - Check if an asset exists
我有一個使用twig模板的symfony2項目。
我正在顯示一些圖像,並且僅在特定資產存在時才顯示圖像。
我有這個:
{% 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條件總是如此。
有什么好主意嗎? 謝謝。
如果要檢查資產是否存在,可以創建一個Twig擴展來實現該功能。
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') %}
注意 :不要忘記替換名稱空間以與項目匹配。
你的代碼中有一個拼寫錯誤:
fuz_tools.twig.asset_exists_extension.class: Fuz\TestBundle\Twig\Extension\AssetsExistsExtension
應該
fuz_tools.twig.asset_exists_extension.class: Fuz\TestBundle\Twig\Extension\AssetExistsExtension
嗨Milos我已經在這里回答了這個問題: https : //stackoverflow.com/a/14232207/875519
只需通過擴展Twig引擎注冊file_exists,然后您就可以在Twig模板內進行測試^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.