Reputation: 275
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?
Upvotes: 1
Views: 6762
Reputation: 317
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.
Upvotes: 2
Reputation: 61
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.
Upvotes: 0
Reputation: 695
http://symfony.com/doc/3.4/best_practices/web-assets.html
Assets function still being usefull in Symfony 4.
Upvotes: 0
Reputation: 425
You can try to use symfony's asset function:
<link rel="stylesheet" href="{{ asset('css/style.css') }}" />
Upvotes: 3