Incorporating a stylish background image into an EJS template

I'm able to successfully display an image from my app.js file in the main ejs file, but when I try to set it as a background image, it doesn't show up. Any thoughts on what might be causing this issue?

This is my app.js file:

const express = require("express"),
  app     = express(),
  bodyParser = require("body-parser"),
  jade = require("jade"),
  path = require('path'),
  redis = require('redis');
  images = [{image:"http://nuvotera.com/wp-content/uploads/2013/10/email-protection-banner-2.jpg"}];

app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine", "ejs");

//render email page
app.get("/email", function(req, res){
  res.render("emailMain", {image:images});
});

app.listen(3000, function(){
console.log("Email Server has started");
});

This is how I'm trying to use the image from the ejs page:

<tr>
<% for(var i=0; i < images.length; i++){ %>

  <td class="vmlHero" background="<%= images[i].image %>" style="background-repeat:no-repeat" bgcolor="#000000" width="100%" height="430" valign="top">

Answer №1

I found the simplest solution to this issue.

ejs file

Include the following code in your CSS file:

body {
        width: 100%;
        align-items : center;
        height: 100%;

        /* Background image is centered vertically and horizontally at all times */
        background-position: center center;

        /* Background image doesn't tile */
        background-repeat: no-repeat;

        /* Background image is fixed in the viewport so that it doesn't move when 
        the content's height is greater than the image's height */
        background-attachment: fixed;

        /* This is what makes the background image rescale based
        on the container's size */
        background-size: cover;

        /* Set a background color that will be displayed
        while the background image is loading */
        background-color: green;
        overflow: hidden;

        /* Location of the image */
        background-image:url('images/introBackGround.jpg') ;
    }  

(remove all blockquotes)

router file

It is essential to add the following code:

app.use(express.static(path.join(__dirname, 'public')));

folder

public
 └ images
  L css 

Answer №2

Having faced a similar situation, I found a solution that worked for me:

<section class="imageHolder" style="background-image: url('<%= img%>')"></section>

Answer №3

Here is the corrected version:

app.get("/email", function(req, res){
  res.render("emailMain", {images: images});
});

Please note the addition of the extra s.

Furthermore, the variable i is not utilized in this part:

<tr>
<% for(var i=0; i < images.length; i++){ %>

  <td class="vmlHero" background = "<%= images.image %>" style="background-repeat:no-repeat" bgcolor="#000000" width="100%" height="430" valign="top">

I believe it should be <%= images[i].image %>, or you may consider using a forEach loop instead.

Additionally, please be aware that the background attribute of td is deprecated. It is suggested to achieve the same effect using either background-image or background within the style properties.

Answer №4

Make a modification in your app.js file:

res.render("emailMain", {image:images});

Change it to:

res.render("emailMain", {images:images});

Next, update the code in your .ejs file:

background="<%= images.image %>"

Update it to:

background="<%= images[i].image %>"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

The eslint script encountered errors when running with meteor npm eslint command

After setting up Eslint, I encountered some errors that I couldn't quite figure out. When running meteor npm run lint, an error was thrown after completing the linting process. To fix this issue, I added the exit 0 attribute to gracefully exit the ...

Oops! Looks like there was an error: weight is not defined when trying to calculate BMI with the HTMLButtonElement

I'm currently working on a project to create a BMI calculator following specific instructions. I've managed to follow all the guidelines except one regarding the letsCalculateBMI function. The instruction states: letsCalculateBMI should extrac ...

Missing Component when Nested within Route in React Router v6

While incorporating the ChoosePlayer component within a Route using React Router v6, <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/players"> <Route element ...

Guide on how to modify a static css file using Node.js

Issue Whenever a user updates the theme on the front-end, my Node.js API needs to update the static CSS file located in a public folder set up by Express. This way, when pages are served again with <link href="public/theme.[userId].[hash].css", the use ...

TemplateUrl malfunctioning

While experimenting with basic Angular code, I encountered an issue where everything was functioning correctly when using template, but not when switching to templateUrl. I did not provide the previous code as it was working fine except for this specific c ...

Understanding JavaScript Regular Expressions

To ensure that no HTML tags are entered into a textarea, I am utilizing the following regex for validation. If any HTML tags are detected in the textarea, I need to display a validation message. The regex being used is: /<(\w+)((?:\s+\w ...

How to modify a variable in the Config.json using a Discord.js command

Lately, I enhanced my bot's functionality by allowing it to retrieve the color for embeds from a file specified in my config.json. All I need to do is modify something like: "embedcolor": "00A950" to "embedcolor": "0 ...

Implementing specific CSS styles for different routes in Angular 5: Use Bootstrap CSS exclusively for admin routes

I am looking to apply Bootstrap CSS only to routes starting with '/admin'. I have enabled lazy loading for both admin and public modules. ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

Easily move a group of HTML elements at the same time with a simple

Exploring HTML5 Drag and Drop with Multiple Elements When it comes to dragging and dropping multiple elements in HTML5, there seems to be a limitation with the default draggable attribute. This attribute allows only one element to be dragged at a time, ma ...

The webpack-bundle-analyzer tool reveals that running webpack -p does not eliminate the development dependency react-dom.development.js

Here is my custom webpack configuration: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const SO ...

Using JavaScript (without jQuery), take away the CSS class from an element

Seeking assistance from experts on the process of removing a class from an element solely using JavaScript. Kindly refrain from suggesting solutions involving jQuery as I am unable to utilize it, and have little knowledge about its functionalities. ...

Exploring ways to retrieve a video thumbnail with VueJS3

I am currently working on a project to create a simple program that retrieves movies from my AWS-S3 bucket and transforms them into picture thumbnails. Below is the code I have written: <template> <img :src="imgURL" class="card- ...

Is it possible to deinitialize data tables (remove from memory)?

I'm currently utilizing data-tables (with jQuery) on my website. The particular data-table I have implemented seems to be consuming excessive memory in javascript, causing a slowdown in other functionalities. Is there a way for me to de-initialize th ...

Implementing Twain functionality in an Electron-based desktop application

I've been tasked with building a desktop application using React + Electron, and my client wants to incorporate scanning documents using a scanner and uploading them to the server through the app. Are there any effective ways to integrate Twain into R ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

An error occurred when attempting to access data within a variable that is undefined, resulting in a TypeError at the errorHandler function

Every time I attempt to send a post, patch, or put request, I keep getting this error. However, there are no issues with get requests. TypeError: Cannot read properties of undefined (reading 'data') at errorHandler (/home/joe/Documents/mypro ...

Determining the necessary data to send via ajax for a particular issue

Currently, I am learning JavaScript and have encountered another challenge along the way. I am looking for assistance in understanding the concept, whether it is a solution in jQuery or Angular. I have two types of tasks in my HTML - audio or graphic. The ...

Extracting data from a Wikipedia table using web scraping in JavaScript

I'm attempting to extract information from a specific website. <script> var convertToInt; var allData = []; $.ajax({ url: "http://en.wikipedia.org/wiki/Demographics_of_Europe", type: 'GET', cache: false, success: func ...