Ronny Susanto
Ronny Susanto

Reputation: 35

EmberJS: How to load assets relative to rootURL or load assets using absolute path

this might be a pretty common question but what I found on google does not help me.

I have a emberJs Project with all assets(images, etc) in my-ember-project/public/assets/images/ everything works fine when i load the assets from homepage which is the root URL "/" or localhost:4200

for example in my homepage I have a component with img tag which looks like this

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

on another page with url localhost:4200**/articles/** I also load the same image with the same tag but from what I've seen it tried to load the image from localhost:4200/articles/assets/images/articles/article-1.jpg and not from the correct path localhost:4200/assets/images/articles/article-1.jpg

adding "/" before "assets/images/" works for me if I'm trying to host my project on root folder but when I need to host my project on subdirectory so my url (www.mydomain.com/ember-project-here/)

how do I load my assets from absolute path or relative to my settings of rootURL adding {{rootURL}} seems to do nothing to me

Upvotes: 1

Views: 957

Answers (3)

Lux
Lux

Reputation: 18240

you can add a path helper:

import { helper } from '@ember/component/helper';
import ENV from 'project-name/config/environment';

export default helper(function([path]) {
    return path.replace(/^~\//, ENV.rootURL);
});

The you can do:

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

This is nice because you can also use variables:

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

and myPath:

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

Upvotes: 1

Gennady Dogaev
Gennady Dogaev

Reputation: 5991

It seems, {{rootURL}} does not work in hbs files (long time ago I used to think it does).

{{env 'rootURL'}} should work, where env is a helper defined like this:

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);
});

Upvotes: 1

Gokul Kathirvel
Gokul Kathirvel

Reputation: 1610

You've done a good research on this front. Yes, rootURL is the one you want to add to your project since you are deploying your application to a subfolder.

rootURL can be added to any Ember app using the config/environment.js file.

// config/environment.js

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

The official guide can give you some additional info!

Upvotes: 0

Related Questions