繁体   English   中英

Symfony 4路由到资产文件夹

[英]Symfony 4 route to assets folder

我试图按照此页面上的说明将样式表加载到我的Assets文件夹中:

https://symfony.com/doc/current/best_practices/web-assets.html

但是我无法使用以下方法从base.html.twig导航到该文件夹​​:

<link rel="stylesheet"  type="text/css" href="/assets/css/style.css" />

我的文件结构如下所示:

templates 
    base.html.twig 
assets
    css
        style.css

任何想法为什么这不起作用?

您可以尝试使用symfony的资产函数:

<link rel="stylesheet" href="{{ asset('css/style.css') }}" />

在您的AppExtension中:

// register function here
public function getFunctions() {
    return [
        new TwigFunction('load_js_asset', array($this, 'fileGetJsAsset')),
    ];
}

// register filter here
public function getFilters() : array
{
    return [
        new TwigFilter('html_entity_decode', 
                       [$this, 'html_entity_decode'], 
                       ['is_safe' => ['html']]),
}

/**
 * @param string $string
 * @return string
 */
public function html_entity_decode(string $string) : string {
    return html_entity_decode($string);
}

/**
 * @param string $file
 * @param bool   $embedScriptTag
 * @return string
 */
public function fileGetJsAsset(string $file, bool $embedScriptTag = true) : string {
    /** @var bool|string $content */
    $content = file_get_contents(__DIR__ . '/../../assets/js/' . $file);

    if ($content === false) {
        throw new FileException('Could not found or read file: ' . $file);
    }

    if (!$embedScriptTag) {
        return $content;
    }

    return '<script>' . $content . '</script>';
}

现在在您的视图中加载js资产,如下所示:

//从根资产/ js文件夹加载

{{ load_js_asset('core/jquery.min.js', true)|html_entity_decode }} {{ load_js_asset('core/popper.min.js')|html_entity_decode }} {{ load_js_asset('my-beauty-js-file.js')|html_entity_decode }}`

希望对您有所帮助。

也许您还需要htmlspecialchars_decode过滤器。

http://symfony.com/doc/3.4/best_practices/web-assets.html

资产功能在Symfony 4中仍然有用。

几个可能的解决方案-如果没有更多细节,我不确定它们是否一定能解决问题:

  • 首先,您是否配置了webpack-encore并运行了构建? 否则,资源将不存在, nginx将生成404尝试路由到该资源。

  • 其次,如果您正在使用Docker运行,则可能未将./app/public/文件夹安装到nginx容器上,以便可以提供文件。 如果转到这些文件时获得Symfony 404,则可能是问题所在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM