简体   繁体   中英

Symfony 4 route to assets folder

I am trying to load the stylesheet in my Assets folder following the instruction giving on this page:

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

But I fail to navigate from the base.html.twig to the folder using:

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

my file structure looks like this:

templates 
    base.html.twig 
assets
    css
        style.css

Any ideas why this doesn't work?

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

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

In your 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>';
}

Now in your view load js assets like this:

// loading from root assets/js folder

{{ 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 }}`

I hope it helps.

Maybe you will need also htmlspecialchars_decode filter.

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

Assets function still being usefull in Symfony 4.

A couple of possible solutions - without more detail I can't be sure if they will definitely solve the problem or not:

  • First, did you configure webpack-encore and run the build? Without that the resources won't be there and nginx will generate a 404 trying to route to it.

  • Second, if you're running with Docker, you may not have mounted the ./app/public/ folder onto the nginx container so that the files could be served. If you are getting a Symfony 404 when you go to those files, this may be the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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