Home  >  Article  >  Web Front-end  >  Passing Data to EJS Templates and Vice-Versa — A Beginner&#s guide

Passing Data to EJS Templates and Vice-Versa — A Beginner&#s guide

DDD
DDDOriginal
2024-09-14 14:30:101076browse

Hey ??‍♂️ ! If you're just starting with EJS (Embedded JavaScript) and wondering how to pass data between your server and EJS templates, you're in the right place! I'm was learing about EJS this whole week, and I wanted to share what I’ve learned about passing data to EJS and how to work with the data.


How to Pass Data from the Server to an EJS Template

So, when you want to send data from your server (Node.js Express) to an EJS template, it’s super simple. You just use the res.render() method, which allows you to send your data from the server to your .ejs file.

Here’s how you do it:

res.render("ejs_file_name", { data });

In this example, we’re rendering an EJS file (let’s say index.ejs) and passing the data object to the template.

Then, to use this data in your EJS template, you simply access it like this:

<%= data %>

Here’s a quick breakdown:

  • res.render() is responsible for sending the data to the template.
  • The <%= data %> tag in EJS is where the passed data is displayed.

Just make sure that the name of the data (like data in this case) is the same in both places (in your server code and in your EJS template). If they don't match, things will get weird!


Wait… What Happens If There’s No Data? ?

Here’s the tricky part: EJS doesn’t check whether the data exists before using it. It just uses the data as if it’s always there. So, if you’re trying to access some data that doesn’t exist (or isn't passed properly), EJS can throw an error and crash your app. That can be super frustrating when you're just starting out!

Passing Data to EJS Templates and Vice-Versa — A Beginner

But don’t worry, there's a simple fix. You can check if the data exists before trying to use it. You can wrap your data inside an if condition like this:

<% if (locals.data) { %>
  <%= data %>
<% } else { %>
  

No data available!

<% } %>

This way, you won’t crash your app if something goes wrong or if the data wasn’t passed. Instead, you can show a fallback message or take a different action.

? Pro Tip: Always check if your data exists in the template before using it — it saves you a lot of headaches!


Challenge Time: Passing Data from EJS to the Server

To make this learning journey fun, I decided to build a simple project that takes a user’s name as input and then tells them how many characters are in their name. Simple, right? Here’s how I did it:

  1. Get the Input Data:
    I used an HTML form that takes a user’s first and last name.

  2. Send Data to the Server:
    Using POST, I sent the input data to the server, and then calculated the character count of the full name.

  3. Send the Processed Data Back to the Template:
    I passed the character count back to the EJS template to display it on the page.

Here’s the server-side code that handles this:

app.post("/submit", (req, res) => {
  const charCnt = req.body["fName"].length + req.body["lName"].length;
  res.render("index.ejs", { charectercount: charCnt });
}); // I used body-parser to get the data from the form
  • req.body gets the form data from the user input.
  • I simply counted the characters in the first and last name and passed that count to the EJS file.
  • The EJS template then displays the character count.

Feel free to check out the full code on my GitHub here: Project Code


In a nutshell ?

That’s a quick summary of how you can pass data to an EJS template and get data back from the client! EJS is super flexible and makes it easy to mix HTML with JavaScript, and learning how to manage data passing effectively opens up a lot of possibilities for your projects.

Here are the key takeaways from this post:

  • Use res.render() to pass data from your server to your EJS template.
  • Always check if your data exists before using it in the template to avoid crashes.
  • You can easily send data back to your server and process it using req.body (for POST requests).

If you're just learning like me, I hope this post made things clearer and helps you avoid some of the early pitfalls. Feel free to leave any questions or comments below! ?

The above is the detailed content of Passing Data to EJS Templates and Vice-Versa — A Beginner&#s guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn