Symfony2-检查文件是否存在
我有一个循环在细枝模板,它返回多个值。最重要的是-我的条目ID。当我没有使用任何框架或模板引擎时,我只是在循环中使用Symfony2-检查文件是否存在,symfony,twig,Symfony,Twig,我有一个循环在细枝模板,它返回多个值。最重要的是-我的条目ID。当我没有使用任何框架或模板引擎时,我只是在循环中使用file\u exists()。现在,我似乎找不到一种方法在树枝上做这件事 当我在标题中显示用户的化身时,我在控制器中使用file\u exists(),但我这样做是因为我没有循环 我尝试在Twig中定义,但它对我没有帮助。有什么想法吗?如果您想检查是否存在一个不是twig模板的文件(这样定义的文件无法工作),请创建TwigeExtension服务并将file_exists()函数
file\u exists()
。现在,我似乎找不到一种方法在树枝上做这件事
当我在标题中显示用户的化身时,我在控制器中使用file\u exists()
,但我这样做是因为我没有循环
我尝试在Twig中定义
,但它对我没有帮助。有什么想法吗?如果您想检查是否存在一个不是twig模板的文件(这样定义的文件无法工作),请创建TwigeExtension服务并将file_exists()函数添加到twig:
src/AppBundle/Twig/Extension/TwigExtension.php
就这样,现在您可以在细枝模板中使用文件_exists())
一些template.twig:
{% if file_exists('/home/sybio/www/website/picture.jpg') %}
The picture exists !
{% else %}
Nope, Chuck testa !
{% endif %}
编辑以回答您的评论:
要使用file_exists(),您需要指定文件的绝对路径,因此您需要web目录绝对路径,为此,您可以访问细枝模板中的网页
app/config/config.yml:
# ...
twig:
globals:
web_path: %web_path%
parameters:
web_path: %kernel.root_dir%/../web
现在,您可以在细枝模板中获取文件的完整物理路径:
{# Display: /home/sybio/www/website/web/img/games/3.jpg #}
{{ web_path~asset('img/games/'~item.getGame.id~'.jpg') }}
因此,您可以检查该文件是否存在:
{% if file_exists(web_path~asset('img/games/'~item.getGame.id~'.jpg')) %}
我和托梅克有同样的问题。我使用了Sybio的解决方案,并做了以下更改:
app/config.yml=>在web\u路径的末尾添加“/”
parameters:
web_path: %kernel.root_dir%/../web/
调用文件_不存在“资产”:
希望这有帮助。我创建了一个Twig函数,它是我在这个主题上找到的答案的扩展。Myasset_if
函数采用两个参数:第一个参数是资产显示的路径。第二个参数是备用资源(如果第一个资源不存在)
创建扩展文件:
src/Showdates/FrontendBundle/Twig/Extension/ConditionalAssetExtension.php:
<?php
namespace Showdates\FrontendBundle\Twig\Extension;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ConditionalAssetExtension extends \Twig_Extension
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Returns a list of functions to add to the existing list.
*
* @return array An array of functions
*/
public function getFunctions()
{
return array(
'asset_if' => new \Twig_Function_Method($this, 'asset_if'),
);
}
/**
* Get the path to an asset. If it does not exist, return the path to the
* fallback path.
*
* @param string $path the path to the asset to display
* @param string $fallbackPath the path to the asset to return in case asset $path does not exist
* @return string path
*/
public function asset_if($path, $fallbackPath)
{
// Define the path to look for
$pathToCheck = realpath($this->container->get('kernel')->getRootDir() . '/../web/') . '/' . $path;
// If the path does not exist, return the fallback image
if (!file_exists($pathToCheck))
{
return $this->container->get('templating.helper.assets')->getUrl($fallbackPath);
}
// Return the real image
return $this->container->get('templating.helper.assets')->getUrl($path);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'asset_if';
}
}
现在在模板中使用它,如下所示:
<img src="{{ asset_if('some/path/avatar_' ~ app.user.id, 'assets/default_avatar.png') }}" />
namespace AppBundle\Twig\Extension;
class FileExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getName()
{
return 'file';
}
public function getFunctions()
{
return array(
new \Twig_Function('checkUrl', array($this, 'checkUrl')),
);
}
public function checkUrl($url)
{
$headers=get_headers($url);
return stripos($headers[0], "200 OK")?true:false;
}
只需对Sybio的贡献添加一点评论:
Twig_Function_Function类自1.12版和
将在2.0中删除。改用Twig_SimpleFunction
我们必须通过Twig\u SimpleFunction更改类Twig\u Function\u函数:
<?php
namespace Gooandgoo\CoreBundle\Services\Extension;
class TwigExtension extends \Twig_Extension
{
/**
* Return the functions registered as twig extensions
*
* @return array
*/
public function getFunctions()
{
return array(
#'file_exists' => new \Twig_Function_Function('file_exists'), // Old class
'file_exists' => new \Twig_SimpleFunction('file_exists', 'file_exists'), // New class
);
}
public function getName()
{
return 'twig_extension';
}
}
改进Sybio的答案,我的版本中不存在Twig_simple_函数,例如,这里没有适用于外部图像的函数。因此,我的文件扩展名文件如下:
<img src="{{ asset_if('some/path/avatar_' ~ app.user.id, 'assets/default_avatar.png') }}" />
namespace AppBundle\Twig\Extension;
class FileExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getName()
{
return 'file';
}
public function getFunctions()
{
return array(
new \Twig_Function('checkUrl', array($this, 'checkUrl')),
);
}
public function checkUrl($url)
{
$headers=get_headers($url);
return stripos($headers[0], "200 OK")?true:false;
}
以下是我使用SF4、autowire和autoconfigure的解决方案:
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Symfony\Component\Filesystem\Filesystem;
class FileExistsExtension extends AbstractExtension
{
private $fileSystem;
private $projectDir;
public function __construct(Filesystem $fileSystem, string $projectDir)
{
$this->fileSystem = $fileSystem;
$this->projectDir = $projectDir;
}
public function getFunctions(): array
{
return [
new TwigFunction('file_exists', [$this, 'fileExists']),
];
}
/**
* @param string An absolute or relative to public folder path
*
* @return bool True if file exists, false otherwise
*/
public function fileExists(string $path): bool
{
if (!$this->fileSystem->isAbsolutePath($path)) {
$path = "{$this->projectDir}/public/{$path}";
}
return $this->fileSystem->exists($path);
}
}
在services.yaml中:
services:
App\Twig\FileExistsExtension:
$projectDir: '%kernel.project_dir%'
在模板中:
# Absolute path
{% if file_exists('/tmp') %}
# Relative to public folder path
{% if file_exists('tmp') %}
我是新来Symfony的,所以欢迎大家发表意见
另外,由于最初的问题是关于Symfony 2的,也许我的答案与此无关,我最好自己问一个新的问题和答案?效果很好,但您能告诉我,我如何检查资产的存在吗?我想:{%if file_存在(asset('images/logo.png'))%}已检查!{%endif%}因为asset()返回媒体的绝对路径,这样它就可以工作并检查正确的路径^^^^这就是我的想法,但是{%if文件存在(asset('img/games/'~item.getGame.id~'.jpg'))%}
不起作用(我的意思是,即使文件存在,它也会返回false).我刚刚编辑了我的答案。我想我在最后检查了解决方案!嗯,web\u路径
工作得很好,但它仍然看不到文件。我想添加它来添加一个参数,以便在twig模板中使用,您需要将其添加到twig config,如前所述
services:
App\Twig\FileExistsExtension:
$projectDir: '%kernel.project_dir%'
# Absolute path
{% if file_exists('/tmp') %}
# Relative to public folder path
{% if file_exists('tmp') %}