【问题标题】:How to use twig asset in a css file?如何在 css 文件中使用树枝资产?
【发布时间】:2022-01-02 01:15:45
【问题描述】:

所以我想使用 CSS 导入字体。 我知道如何在 twig/html 页面中使用 {{ asset('')}} !但我不知道如何在 CSS 文件中做到这一点!

当前css文件代码为:

@font-face {
  font-family: 'porta';
  src: url("../fonts/pluton.eot?49924914");
  src: url("../fonts/pluton.eot?49924914#iefix") format("embedded-opentype"),
       url("../fonts/pluton.woff?49924914") format("woff"),
       url("../fonts/pluton.ttf?49924914") format("truetype"),
       url("../fonts/pluton.svg?49924914#porta") format('svg);
  font-weight: normal;
  font-style: normal;
}

我做了什么:

@font-face {
  font-family: 'porta';
  src: url("{{ asset('../fonts/pluton.eot?49924914') }}");
  src: url("{{ asset('../fonts/pluton.eot?49924914#iefix') }}") format("embedded-opentype"),
       url("{{ asset('../fonts/pluton.woff?49924914') }}") format("woff"),
       url("{{ asset('../fonts/pluton.ttf?49924914') }}") format("truetype"),
       url("{{ asset('../fonts/pluton.svg?49924914#porta') }}") format("svg")
  font-weight: normal;
  font-style: normal;
}

我添加了这样的资产,但它没有用!那么如何正确添加 CSS 文件呢?

【问题讨论】:

  • css 文件通常只是从 web 服务器 (nginx/apache) 交付,因为这正是 symfony 公用文件夹中的所有内容所发生的情况。如果要在 css 文件中使用 twig,则必须为该 css 文件创建一个控制器 + 路由,将 css 文件视为 twig 模板等等。我不认为这实际上是一个好主意。问题是:你为什么要这个?因为我看不出有什么好的理由……
  • 我只是从网上下载了一个模板,并在我的 symfony 项目中使用它
  • 简单的解决方案是:不要在 static 文件中使用 twig 函数(例如asset)。当你在public 文件夹中放一些东西时,它们通常是静态的。只能在模板文件中使用 twig 函数,而模板文件是由控制器使用的。

标签: php css symfony twig include


【解决方案1】:

asset() 是一个 twig 函数,你不能在 css 文件中使用 twig 函数。如果您想捆绑您的资源,例如图像、字体、css、js 等,请使用 webpack,或者如果您使用 php >= 7.1,请使用 webpack encore

【讨论】:

  • 我不知道该怎么做,因为我不是做前端的人,我只是从互联网上下载了一个模板,我正在做后端!我在实现字体文件时发现了一个问题!
  • 好吧,我不知道谁没有前端,但通常如果字体/前端相关的任何东西都在 web / public 文件中并且你的 css 在 web/css / public/css 中,通常的路径是../images 或 ../fonts ../webfonts ../anything
猜你喜欢
  • 1970-01-01
  • 2015-11-24
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多