[英]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.