Yii2 Advanced 模板中前端和后端共享资源

问题描述 投票:0回答:3

我一直在尝试从项目的前端和后端加载简单的 CSS (custom.css)。

CSS位于

frontend/views/web/css/custom.css

它在前端加载没有问题。这是位于前端的 AppAsset 文件:

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

/**
 * Main frontend application asset bundle.
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
        'css/custom.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

所以我只是认为位于后端的AppAsset文件应该如下所示:

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

/**
 * Main backend application asset bundle.
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/custom.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

但是加载后端索引时我得到的只是这样:

http://localhost:8888/backend/web/css/custom.cssFailed to load resource: the server responded with a status of 404 (Not Found)

如何在前端和后端之间共享CSS?

yii2 assets
3个回答
1
投票

执行此操作的一种直接方法是在应用程序根目录下有一个通用的可访问 Web 的文件夹。类似 /assets 的东西,您可以从后端和前端访问。您还需要编辑 .htaccess 以允许这样做。

只有设置了 $sourcePath 并且未设置 $basePath 和 $baseUrl 时,Yii2 才会发布资源(!)

因此:

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
   public $sourcePath = '@app/assets/app';

 public $css = [
   'css/openbook.css',
   'fontello/css/fontello.css',
   'fontello/css/animation.css'
 ];
 public $js = [
   'js/plug.openbook.js',
   'js/plug.interpret.js',
   'js/plug.drop.message.js'
 ];
 public $depends = [
   // 'yii\web\YiiAsset', 
   // 'yii\bootstrap\BootstrapAsset',
 ];
}

在主布局中:

use frontend\assets\AppAsset;
   ...
AppAsset::register($this);

1
投票

如果你想加载共享资源,即 js 或 css ,在 YourAsset 类中 sourcePath 必须是“@yourSource/web/”, 例如,如果您想在前端加载位于 common/web/css/ 目录中的 css 文件,您的 AppAsset 或任何其他自定义资产类位于 common/ 中,则必须初始化以下变量

公共$sourcePath =“@common/web”; 公共$basePath =“@common”;

注意:“@ewbroot”路径和$baseUrl =“@web”将定位到您当前的访问路径,在本例中为前端 & 将加载它 “本地主机/yii-application/frontend/css/filename.css” 所以你必须省略它。


0
投票

您可以在任何视图或布局本身上注册文件

<?php $this->registerCssFile('http://domain.com/frontend/web/path/file.css');?>

您还可以在资源包中添加完整路径

public $css = [
    'http://domain.com/frontend/web/path/file.css',
];
© www.soinside.com 2019 - 2024. All rights reserved.