【问题标题】:EmberJS: How to load assets relative to rootURL or load assets using absolute pathEmberJS:如何加载相对于 rootURL 的资产或使用绝对路径加载资产
【发布时间】:2020-04-26 15:47:42
【问题描述】:

这可能是一个很常见的问题,但我在谷歌上找到的内容对我没有帮助。

我有一个包含所有资产(图像等)的 emberJs 项目 我的余烬项目/公共/资产/图像/ 当我从根 URL“/”或 localhost:4200 的主页加载资产时,一切正常

例如在我的主页中 我有一个带有 img 标签的组件,看起来像这样

<img src="assets/images/articles/article-1.jpg"/>

在另一个带有 url localhost:4200**/articles/** 的页面上,我还加载了具有相同标签的相同图像 但据我所见,它试图从 localhost:4200/articles/assets/images/articles/article-1.jpg 而不是从正确的路径 localhost:4200/assets/images/articles/article-1 加载图像.jpg

如果我想在根文件夹中托管我的项目,在“assets/images/”之前添加“/”对我有用 但是当我需要在子目录上托管我的项目时,我的 url (www.mydomain.com/ember-project-here/)

如何从绝对路径或相对于我的 rootURL 设置加载我的资产 添加 {{rootURL}} 似乎对我没有任何作用

【问题讨论】:

    标签: html ember.js


    【解决方案1】:

    看来,{{rootURL}} 在 hbs 文件中不起作用(很久以前我曾经认为可以)。

    {{env 'rootURL'}} 应该可以工作,其中env 是一个这样定义的助手:

    import { get } from '@ember/object';
    import { helper } from '@ember/component/helper';
    import ENV from 'project-name/config/environment';
    
    export default helper(function([path]) {
      return get(ENV, path);
    });
    

    【讨论】:

    • 谢谢你这是完美的!正是我正在寻找的。​​span>
    【解决方案2】:

    您可以添加一个path 助手:

    import { helper } from '@ember/component/helper';
    import ENV from 'project-name/config/environment';
    
    export default helper(function([path]) {
        return path.replace(/^~\//, ENV.rootURL);
    });
    

    你可以做的:

    <img src={{path "~/assets/images/articles/article-1.jpg"}} />
    

    这很好,因为您也可以使用变量:

    <img src={{path this.myPath}} />
    

    myPath:

    get myPath() {
      return `~/assets/images/${this.args.iconName}.jpg`;
    }
    

    【讨论】:

      【解决方案3】:

      您在这方面做了很好的研究。是的,rootURL 是您想要添加到项目中的那个,因为您正在将应用程序部署到子文件夹中。

      rootURL 可以使用config/environment.js 文件添加到任何 Ember 应用程序。

      // config/environment.js
      
      module.exports = function(environment) {
        var ENV = {
          // other configs...
          rootURL: '/ember-project-here/',
        };
      }
      

      The official guide 可以给你一些额外的信息!

      【讨论】:

      • 我也这样做了,但是将 {{rootURL}} 添加到 src 不会将 src 从检查更改为 ember-project-here/assets/images/articles/article-1.jpg元素菜单是 assets/images/articles/article-1.jpg 好像 {{rootURL}} 什么都不做。我是否必须以某种方式将 rootURL 数据提取到我的模型中?顺便说一下,我正在尝试在模板和组件中使用 rootURL。我错过了什么?我也尝试这样做&lt;h1&gt;{{rootURL}}&lt;/h1&gt; 看看我的 {{rootURL}} 输出什么
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 2018-03-27
      • 2016-08-10
      • 1970-01-01
      相关资源
      最近更新 更多