user9235723
user9235723

Reputation:

How to include static image in html template?

Static images are not displayed in html template.
I'm using JHipster 4.14.1 - Angular 5 - webpack 3.10.0

I put my image in this folder : /webapp/content/images
I use this tag in html template : <img scr="../../content/images/hello.png" alt="hello the world">

My webpack config seems to be ok according this link which describe the same problem.
Jhipster4, Angular2: How include static image in html

My "webpack.common.js" file contains :

test: /\.html$/,
       loader: 'html-loader',
       options: {
           minimize: true,
           caseSensitive: true,
           removeAttributeQuotes:false,
           minifyJS:false,
           minifyCSS:false
       },
       exclude: ['./src/main/webapp/index.html']
   },
   {
       test: /\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/i,
       loaders: ['file-loader?hash=sha512&digest=hex&name=content/[hash].[ext]']
   },

Generated filenames are hashed. So, I opened each PNG image generated in the folder target/www/content and I don't find my image.

What's wrong ?

Upvotes: 0

Views: 11968

Answers (3)

user9235723
user9235723

Reputation:

In my JHipster environment, the only way I found was to add a selector to the home.scss file like this :

.hello {
    height: 150px;
    background: url("../../content/images/hello.png") no-repeat center;
    background-size: contain;
}

To show my image in a HTML template I used :
<div class="hello" ></div>

If I don't reference the image in the .scss file, the PNG image in the webapp/content/image is not copied to the target/www/content folder.

Are there other workarounds that are simpler to implement to display a static image in html template ?

Upvotes: 0

Jon Ruddell
Jon Ruddell

Reputation: 6362

You are missing the content directory from your image path. To include images in Angular:

<img src="../../content/images/hipster.png" alt="Hipster" />

Note that the number of ../ to include depends on how many directories deep you are relative to the content folder

Webpack hashes the image when compiling the TS and templates, so it will be in /target/www/content/ but under a different name. The generated output from Webpack:

<img _ngcontent-c1="" alt="Hipster" src="content/ca854e6d0785ba4b9d715049c0bdbcb3.png">

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86790

Put all your images in the assets folder and try to fetch from there like this -

<img scr="assets/images/hello.png" alt="hello the world">

Upvotes: 0

Related Questions