Trying to switch between local and public webpage while looping through data - html

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>

Related

Is there literally any way to get whitespace filenames to work with <img src="...">?

I have a file named "Ashen Valley-Thumbnail.jpg".
For my own sanity, I would rather not replace every single space in every single filename manually with a "valid" encoding like %20, which is the only way to fix this outside of writing a program to do it for me (which would take even longer). My goal is to be able to transfer my named files directly into the source folders (with spaces!) without having to rename them.
I've tried literally every trick in the book, namely name_of_file.replace(/ /g, "%20"), putting the name in quotes for the srcurl, and encodeURI(name_of_file), the only three answers the internet seems to have for this question. None of them worked.
I'm using React and Node.js with Express. In my server.js file, I have a fs.readdirSync block that returns all file names in a directory. The function takes the file names and tries to make an <img> from the file name and the path.
There are no errors in my code, so, I don't need to type it out. I just need someone to tell me if what I'm trying to accomplish is at all possible.
EDIT:
Some clarification:
The context I'm using <img src="..."> in:
props.artwork.map(genre => {
return(
<div className = "genre">
<h2 className = "genre-name">{genre.name}</h2>
<hr></hr>
<div>
{genre.array.map(image => {
let name = image.replace(/=|-Thumbnail|.jpg|.png/g, " ");
return (
<div className = "thumbnail">
<img src = {"/images/Artwork/Concept/thumbnails/Ashen Valley-Thumbnail.jpg"} alt = {"" + name + ""}></img> // THIS IS THE PROBLEM AREA *************
<p>{name}</p>
</div>
)
})}
</div>
</div>
)
The src above works when the file name is "Ashen=Valley-Thumbnail.jpg" and I type "Ashen=Valley-Thumbnail.jpg" in the src.
This is in React, part of a functional component's return(...)
Strictly going by your title question. It sounds like you're wondering ...
Is there literally any way to get whitespace filenames to work with
<img src=“…”>
I just tried experimenting within my own local react app by adding a basic jsx image tag to my page.
<img width="300" src={"./images/potter space media.jpg"} alt={'stack-overflow-test'} />
I then dragged a random jpg from my desktop into my project.
I was eventually able to prove that yes, you can render an image that has spaces in its name. I was able to get "potter space media.jpg" to render correctly.
See Example here:
Things to Note:
it matters where you save or store your images. Are you storing them under "./public" vs. "./src" ?
I found this question and answers helpful Correct path for img on React.js
`
You might want to take advantage of modularizing your components. This is an example of what you are trying to do. I would expect this kind of modularity from a professional PR. Otherwise, you may be doing something else fundamentally wrong. Use a custom <Img /> component for your images:
// Modular hook
function useEncodedURI(uri) {
const [encoded, setEncoded] = useState();
useEffect(() => { setEncoded(encodeURI(uri)) }, [uri]);
return encoded;
}
// Replace all <img /> with <Img />
function Img({ src, ...rest }) {
const encodedSrc = useEncodedURI(src);
return <img src={encodedSrc} {...rest} />
}
Don't use <img />. If you want consistency, just replace all <img /> with <Img />. Any decent text editor can swath over this change in a few keystrokes.

How to add images in an html file?

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>

ASP.NET MVC Img tag not loading image when loading path from database

I am attempting to make a photo gallery asp.net MVC website, and part of that involves the setting of the src to a local folder that contains images.
#model MyProj.Models.PhotoIndexViewModel
<div class="row" id="tableSearch">
#foreach (MyProj.Models.VideoModel photo in Model.PImgList)
{
<div class="col-sm-3 thumbnail">
#Html.DisplayFor(model => photo.Title)
<a href=#Url.Action("View", new { id = photo.Id })>
<img class="img-responsive"src="#Url.Content(photo.ThumbNailPrev)" alt=#photo.Id /></a>
#Html.HiddenFor(m => m.searchTerm)
#Html.Partial("_Tags", photo)
</div>
}
</div>
The ThumbNailPrev is "~/Pics/.jpg", which relates to a folder in the main part of the project. The issue is that the image does not appear. When I check the image using inspector is says it isn't found at /Pics/(photoid)/jpg. I don't understand why it is doing this, as my pics and the image itself are present at that location. I have also made sure to include the folder in my project, but it still doesn't seem to find the image.
UPDATE:
I just tried something and confirmed it is something to do with the way I'm calling the path from the database. As if I hard code the EXACT same string as the one in the database it works. The question now is why does that work?
For want of a letter..
I finally determined the problem, and it was a pretty dumb one. In code I am saving a jpEg image, but calling it via jpg. After changing the .jpg to .jpeg in the view everything works... If you are having a similar problem, check and make certain the file extension is correct.

Ghost Custom Pagination

I just design a theme for ghost blogging platform, by reading the ghost theme documents. all I need now is customizing the pagination. the document says create a pagination.hbs inside the partial folder. but the problem is I don't know how should the markup be.
There's a brief post here that explains where to find the relevant bit of code for your pagination.hbs file. You'll actually be able to use the default pagination code as your template.
As that post notes, you need to copy the default pagination code from core/server/helpers/tpl/pagination.hbs in the Ghost source code and use it to create your own pagination.hbs file in the partials directory of your theme.
You'll see the markup that you need to edit there, i.e.:
<nav class="pagination" role="pagination">
{{#if prev}}
<a class="newer-posts" href="{{pageUrl prev}}">←</a>
{{/if}}
<span class="page-number">Page {{page}} of {{pages}}</span>
{{#if next}}
<a class="older-posts" href="{{pageUrl next}}">→</a>
{{/if}}
</nav>
You'll need to restart Ghost after saving your edits to see the changes.
I have created some JavaScript code that extends the default Ghost pagination. Instead of showing "Page 1 of X", it shows a row of page numbers with previous, next, first, and last buttons. It also has an ellipsis in the center for sites with a lot of pages. It is fully customizable from the Code Injection settings page.
My implementation creates a bootstrap pagination component, but I'm pretty sure you could output whatever you wanted given the classes and elements that are created (<nav> and <ul> elements).
Here is some code that I include before the {{ghost_foot}}. That way, I can override some of the settings in the Footer section of the Code Injection:
var prev;
var pages;
var page;
var next;
var pageUrlPrev;
var pageUrlNext;
var numbersSurroundingEllipses = 3;
var useSimplePagination = false;
Here is the pagination.hbs for the customized pagination that I am using on my site:
<script type="text/javascript">
// set the values that we'll use in the bootstrap-pagination.js file
{{!if there is no value for the variable, display a 0}}
prev = {{#if prev}}{{prev}}{{else}}0{{/if}};
pages = {{#if pages}}{{pages}}{{else}}0{{/if}};
page = {{#if page}}{{page}}{{else}}0{{/if}};
next = {{#if next}}{{next}}{{else}}0{{/if}};
pageUrlPrev = '{{pageUrl prev}}';
pageUrlNext = '{{pageUrl next}}';
pageUrlFirst = '{{pageUrl 1}}';
pageUrlLast = '{{pageUrl pages}}';
</script>
<nav>
<ul class="pagination bootstrap-pagination">
</ul>
</nav>
Here is the javascript code that will add the pagination to the above HTML.
Note: since these links are created on the client, they will not be available to search engines during indexing. However, it is my understanding that the search engines utilize the link rel="prev" and link rel="next" tags that Ghost outputs for each of the index pages.
Here is what they look like for my website:
<link rel="prev" href="https://cerkit.com/page/2/" />
<link rel="next" href="https://cerkit.com/page/4/" />
That leads me to believe that search engines can navigate between pages and access all links. However, I have not confirmed this with anyone who would know for sure, so do some research if you think this might be an issue.
I also made sure that I submitted my Ghost sitemap link to the search engines just to make sure.
This gives you another option when working with pagination.
Here is the full write-up on my blog that gives a few more details.
I have all of this (and a few other Ghost tricks like binding Font Awesome icons to navbar links) on my website: cerkit.com.

Custom color scheme for CSS

How can I create and load a color scheme on my HTML site using CSS?
I have base.css green.css and orange.css. Now, when site is loaded default color scheme is green, but how to change it to orange.css on the client side?
I want each user to choose color scheme suitable for him. Also the choice must be saved for next visit of this person on site. Something like this in that IPBoard skin (feature called "Color themes") http://www.skinbox.net/skins/velvet/
If you're looking to swap stylesheets on the frontend, and want to save the preference, you can do something like this (using jQuery for simplicity):
In the <head>
<link id='theme' href='green.css' type='text/css' />
In the <body>
<a id='green' href='#'>Click here for green theme</a>
<a id='orange' href='#'>Click here for orange theme</a>
In the javascript file
$(document).ready(function(){
if( localStorage.theme )
$('link#theme').attr('href', localStorage.theme);
$('#orange').click(function(){
$('link#theme').attr('href', "orange.css");
localStorage.theme = "orange.css;"
})
$('#green').click(function(){
$('link#theme').attr('href', "green.css");
localStorage.theme = "green.css;"
})
});
The above code would output two links which switch a CSS file's location on click, thus changing the theme. It also saves the last selected theme in localStorage so that it's remembered.
In general you should do this on the serverside end of things - memorize preferences using cookies or sessions (and/or database tables behind them) and then just generate the correct stylesheet reference in your HTML.
IPB does the same internally, it stores your preferences in a database table and then renders the correct <link rel="stylesheet"> element in its template engine.
Alternatively you could do it completely in Javascript, loading stylesheets on demand, but that is both an advanced topic and generally an inferior solution to a solid serverside implementation.
You could store the default css color scheme file path in a cookie when your index page is loaded, if it is not already set.
Then when you are declaring your css file, simply do;
<link rel="stylesheet" href="https://[YOUR_DOMAIN]/themes/[COOKIE VALUE].css" />
You could then have a change theme button which when clicked will access and change that cookie value to the new theme css file path.
Use Javascript to load selective css onClick.
OR
Use jQuery to change color scheme onMouseClick.