I use Thymeleaf for the templates of a web application.
When I make a link I use a URL like this:
<img class="info"
src="../../../resources/img/image.png"
th:src="#{/resources/img/image.png}" />
How can I configure the base URL in Thymeleaf?
I need this because my application runs in the current URL:
http://localhost:8080/myapp
And it works fine, but then it redirects to:
http://www.myapp.com/
Then the images was search in:
http://www.myapp.com/myapp/resources/img/image.png
instead of:
http://www.myapp.com/resources/img/image.png
I want something like:
<property name="baseURL" value="http://www.myapp.com"/>
Try Server-relative URLs:
<img class="info" th:src="#{~/resources/img/image.png}" />
UPD
Actual link to url part of Thymeleaf 2.1. tutorial
You can pass the baseUrl as parameter to template. Then: <a th:href="${baseUrl + '/my/uri?maybe=' + someParam}". Hope that helps.
Related
At the moment, I am trying to list projects on a website in a grid. Some of them link to another page on the site and others link to another domain page. At the moment I am using React-Router's 'Link' to go from one page to another, however this doesn't work when going to a page outside of the domain. In the JSON file, I check for the 'url' variable which returns either the URL if its public or 'project-page' if it is local. I can't figure out how to differentiate between the two in JSX; is there a work around while still utilizing the JSON file?
<div className="projects">
{projectData.map((projectDetail, index) => {
return(
<div className='project-card'>
<Link to={projectDetail.url}>
<img src={require('./images/icons/' + projectDetail.alt + '.jpg')} alt={projectDetail.title}/>
<h3>{projectDetail.title}</h3>
<p>{projectDetail.subtext}</p>
</Link>
</div>
)
})}
</div>
Well, to differentiate you can check the content of the projectDetail.url you are retrieving from that JSON in your javascript file, if that matches your domain (your website - having a project-page as you mention) or is it an external domain. You can also set a flag value in your json file. For each project set a value (e.g externalUrl: 1 or 0) and then check if projectDetail.externalUrl is 1 (it contains an external link). Then, maybe try the following for external domains:
<Link to={{ pathname: "external URL" }} target="_blank" />
In your case:
<Link to={{ pathname: projectDetail.url }} target="_blank" />
See this answer for detailed information: React-Router External link
Edit 1
If Link does not work for external websites, this would probably be related to the version of react-router you are using. Actually, to navigate to external websites you can as well use anchort tags <a> to redirect. Check what URL your project has and then conditional render a <Link> or <a>.
<a href="www.example.com" target=_blank></a>
In my Angular 4 app, I am using innerHTML to show description of the exercises which are in HTML format.
<li *ngFor="let exercise of exercises">
<div [innerHTML]="exercise.longDescription"></div>
</li>
These descriptions can also contain images
<img src="/file/na\6ad7k4ynon6yh2qcibcdqxwcey.jpg">
and that is where I am struggling because I need to set the base href for these images to localhost:8080 where my backend is. Angular is trying to get them from standard localhost:4200 (ng serve) so I am getting errors.
Any idea how to do that?
Found a solution, not sure if is the cleanest one but it gets the job done.
I created a function in my exercise model that adds environment.URL to the src (which is localhost:8080 for development and server's API for production).
public getHTML () {
return this.longDescription.replace(/<img src="([^"]+)">/, '<img src="'+environment.URL+'$1">');
}
and I access it like this
<div [innerHTML]="exercise.getHTML()"></div>
instead.
Environment const looks like this:
export const environment = {
production: false,
URL: 'http://localhost:8080'
};
I'm pretty new to Angular so I'm not sure the best practice to do this.
I used angular-cli and ng new some-project to generate a new app.
In it created an "images" folder in the "assets" folder, so now my images folder is src/assets/images
In app.component.html (which is the root of my application), I put
<img class="img-responsive" src="assets/images/myimage.png">
When I do ng serve to view my web application, the image does not display.
What is the best practice to load up images in an Angular application?
EDIT: See answer below. My actual image name was using spaces, which Angular did not like. When I removed the spaces in the file name, the image displayed correctly.
In my project I am using the following syntax in my app.component.html:
<img src="/assets/img/1.jpg" alt="image">
or
<img src='http://mruanova.com/img/1.jpg' alt='image'>
use [src] as a template expression when you are binding a property using interpolation:
<img [src]="imagePath" />
is the same as:
<img src={{imagePath}} />
Source: how to bind img src in angular 2 in ngFor?
I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png worked.
Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes.
For example :
'my-image-name.png' should be 'myImageName.png'
'my image name.png' should be 'myImageName.png'
If you put the image in the assets/img folder, then this line of code should work in your templates :
<img alt="My image name" src="./assets/img/myImageName.png">
If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.
Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.
Sample example
<img [src]="'assets/img/klogo.png'" alt="image">
Normally "app" is the root of your application -- have you tried app/path/to/assets/img.png?
1 . Add this line on top in component.
declare var require: any
2 . add this line in your component class.
imgname= require("../images/imgname.png");
add this 'imgname' in img src tag on html page.
<img src={{imgname}} alt="">
You can follow the below steps in Angular 8+
Step 1: load the image as below in component
const logo = require('../assets/logo.svg').default as string;
#Component({
selector: 'app-show-image',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class ShowImageComponent implements OnInit {
logo = logo;
constructor() { }
ngOnInit() { }
}
step 2: Add the logic in html file
<img [src]="logo" [alt]="'logo'">
If launched without further configuration, you will see a strange error:
ERROR in src/app/app.component.ts(4,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i #types/node` and then add `node` to the types field in your tsconfig.
Do as suggested – add the #types/node typings to your project by running npm install #types/node and edit tsconfig.app.json to set:
"compilerOptions": {
"types": ["node"],
...
}
For more info
resource
It is always dependent on where is your html file that refers to the path of the static resource (in this case the image).
Example A:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yourpage.html
As you can see, yourpage.html is one folder away from the root (src folder), for this reason it needs one amount of ../ to go back to the root then you can walk to the image from root:
<img class="img-responsive" src="../assests/images/myimage.png">
Example B:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yoursubmodule
|__yourpage.html
Here you have to go u in the tree by 2 folders:
<img class="img-responsive" src="../../assests/images/myimage.png">
for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.
Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.
Try not give space while loading the images.
Instead of
<img src='assets/img/myimage.png' alt="">
try with string interpolation or Property Binding to load the source image as best practice.
Anytime I have read an article on html and images, I have seen an anchor tag like this:
<img src="http://www.tizag.com/pics/htmlT/sunset.gif" />
However, in my case I have stored the image in AWS-S3 and I am reading image from S3. This, I do not upfront have a path like "http://www.tizag.com/pics/htmlT/sunset.gif"
So what is the most common technique to embed image in the html page when image is stored in S3, and the path to image is not known ?
In case my question is confusing, I will ask it differently.
I am building a project, which is simple. Whenever user is logged in he gets a page saying "Welcome" and below welcome note is is profile picture.
But, assume I have 10 users, each of these 10 users will have a different URL to the image.
eg:
<img src = "http:bucket.amazonaws.com/USER1'> for user 1
<img src = "http:bucket.amazonaws.com/USER2'> for user 2
and so on.
So the image I will display is not known until run-time and path to image is dependent on who logs in.
How to make my HTML page smart so that the image src is not a constant and can be made flexible depending on who logs in ?
SOLUTION IN JSP, WHICH I COULD DO, THANKS TO SO MANY ANSWERS:
<body>
<% String url = (String)request.getAttribute("url"); %>
<img src = <%= url %>></img>
</body>
This JSP code is called from the servlet.
request.setAttribute("url", "URL to image.");
RequestDispatcher view = request.getRequestDispatcher("URLImage.jsp");
view.forward(request, response);
You require some kind of server side programming language to generate the the paths for the image dynamically for each user. Anyway you do have a setup for the users to login. For that, I believe you have some kind of framework in some server side scripting language like PHP(Laravel, Wordpress, CodeIgniter), Java(Spring), Ruby(Rails), Python(Django).
So when a user logs in, your login script should validate the user and you will render a particular html page. And you should show the name of the user and a particular image. In PHP or Ruby on Rails you can embed the actual PHP code or ruby code in HTML.
In PHP, like this :
<html>
<head> </head>
<body>
<!-- say PHP Session varibale contains the logged in user's name & bucket name -->
<img src="<?php echo "https://"+ $_SESSION["bucket_name"] +".amazonaws.com/"+$_SESSION["username"] ?>" />
</body>
</html>
In Ruby on Rails, like this:
<html>
<head> </head>
<body>
<!-- say Ruby - Rails controller passes #username & #bucketname to view -->
<img src="<%= "https://"+ #bucketname +".amazonaws.com/" + #username %>" />
</body>
</html>
In Python - Django, like this :
<html>
<head> </head>
<body>
<!-- In Python - Django Suppose you pass context variables username & bucketname to template -->
<img src="https://{{ bucketname }}.amazonaws.com/{{ username }}" />
</body>
</html>
So what I would suggest is, you get familiar with the server side scripting language that you intend to use or are already using and manipulate the url to be generated based on logged in user accordingly.
If your bucket was named my-bucket and the image file was named my-image.png, then the format for the url would be http://my-bucket.s3.amazonaws.com/my-image.png.
In order to access the file though, you need to have a policy attached to your bucket that allows anyone to access the file. Below is a policy that works for this example.
{
"Id": "some-policy-id",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "some-statement-id",
"Principal": "*",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-bucket/my-image.png"
}]
}
See the docs for more information about accessing a bucket.
Also note that the bucket name must be DNS compatible for this to work. See here under Rules for Bucket Naming.
My suggestion is:
<img src = "http:bucket.amazonaws.com/USER1'> for user 1
<img src = "http:bucket.amazonaws.com/USER2'> for user 2
according to your examples in user1 and user2 having same path is http:bucket.amazonaws.com/ make it common for all and put variable after that and according to your user id fetch image from there.
like <img src = "http:bucket.amazonaws.com/<?php echo $userimg; ?>'
or fetch img path from database according to users
You can use javascript / jQuery:
<script type="text/javascript">
$(document).ready(function(){
var userName = getUserNameValue;
document.getElementById("<%= loginImg.ClientID %>").src = "http:bucket.amazonaws.com/" + userName;
});
</script>
with html:
<img id="loginImg" src="default.img" />
You should be able to handle this like a simple 'insert your name here' kind of Hello World exercise.
Since the user is logged in, you should have at least some sort of information from the user, or can get it - username, first/last name, uniqueID, etc. Ideally when the user logs in, your server will provide you with an image filename, but whatever.
Store that uniqueID into a variable in your JS. This will be used to build your URL in JS.
Then, have the root path of your images in a separate variable.
var uniqueID = 'avatar_e2fbfbcbb52d_128'; // from login
var urlPrefix = 'http://www.tizag.com/pics/htmlT/';
var imageURL = urlPrefix + uniqueID + '.gif';
var imgNode = document.createElement("IMG");
imgNode.src = imageURL;
document.getElementById('imageDiv').appendChild(imgNode);
Then, in your HTML,
<div id='imageDiv></div>
I can tell you the approach since you don't have a code to edit or look into.
You can have an ajax call to your server once the user logged in, get the image URL from there or if you are having any back-end language then get the url from there.
Now the hard part, assigning the URL to the img source tag, so if you are doing the ajax call just store the data(URL) into the JavaScript variable and give img src as that variable, if you are doing it using server side language then also you can do the same, different languages have different way to do it and you need to google it out, or you can have the hidden field with id, assign that hidden field that value (URL) in your JSP or ASP page and use that in the img src.
Hope the approach works. I am a dot net developer and you are java developer so can't tell you the exact code.
Its very simple just try this out. I have added your image path just run this code.
<!DOCTYPE html>
<html>
<body>
<h2>Spectacular Mountain</h2>
<img src="http://www.tizag.com/pics/htmlT/sunset.gif" style="width:304px;height:228px;">
</body>
</html>
I have a mvc 4 project where I am using image references that look like this:
<img alt="Progress Update" class="projectListNotificationIcon" src="#Url.Content("~/Images/progressUpdateIcon.png")"/>
The #Url.Content is necessary for it to work on both the local copy of this project, as well as the live server copy. This works great, however I have another place where I am choosing between 2 different images and tha code looks like this:
var imagePath = (item.IsOverdue) ? "../../Images/lateIcon.png" : "../../Images/onTimeIcon.png";
How can I use some permutation of the #Url.Content in my if statement above? The current way that I am doing it works in the local project, but not on the server.
Try:
<img src="#((item.IsOverdue) ? Url.Content("~/path/img1.jpg") : Url.Content("~/path/img2.jpg"))" alt="whatever" />
Use of the tilde (~) sign is probably the key, as that resolves the url relative to the root of the site.
<img src="#(item.IsOverdue ? "~/path/img1.jpg" : "~/path/img2.jpg")" />
With asp.net mvc 4 urls that begin with the ~ symbol are automatically translated to site relative paths. Read about it here http://www.davidhayden.me/blog/asp.net-mvc-4-the-new-tilde-slash-feature-in-razor-2