Silverstripe - 包括样式表和脚本

问题描述

我已经设置了 Silverstripe 的全新安装并创建了一个主题。 现在我想在 Page.ss 中包含一个 CSS,但我收到一条错误消息,指出无法找到该文件。 我想将主题文件夹中的文件包含在“my-site/themes/my-theme/css/style.css”下。但是,使用“themedCSS('style')”的集成仅在文件再次集成到“my-site/public/_resources/themes/my-theme/css/style.css”下时才有效。我已经尝试了所有变体,但只有当两个地方同时存在 CSS 文件时它才有效。

因为我无法想象这是最佳实践,所以我想知道我错过了什么。此外,“/themes/my-theme/css/style.css”下的样式将被完全忽略(如果两者都包含)。

enter image description here

解决方法

在 SilverStripe 版本 4 中,您希望浏览器能够请求的所有资源文件都必须在 public 文件夹中可用。 您无需手动将文件从应用主题文件夹复制到公共文件夹,您可以做的是定义要在 composer.json 文件中公开的文件。

// composer.json
...
"extra": {
        ...
        "expose": [
            "themes/my-theme/css","themes/my-theme/js",// Any other files or folders you want to expose
        ]
    },

然后,当您在终端中运行 composer vendor-expose 命令时,它会将列出的文件公开到公共文件夹。

默认情况下,暴露命令将在公共和项目文件夹之间创建一个符号链接,因此您的所有更改也将反映在那里,这样您就不需要在每次更改后运行暴露命令,只有在添加时要公开的新文件。

也可以通过页面控制器导入资源文件,如下所示:

// A page controller,e.g. "PageController.php"

    protected function init()
    {
        parent::init();
        self::myImports();
    }

    private static function myImports() {
        // Files must be available in the public folder:
        // - "/public/_resources/themes/my-theme/css/app.css"
        // - "/public/_resources/themes/my-theme/js/app.js"
        Requirements::css('./themes/my-theme/css/app.css');
        Requirements::javascript('./themes/my-theme/js/app.js');
    }