In the last post, I shared an example to show you how to render a HTML page from a EJS file. And, I also mention that this way has limitation because users will receive the same page every time.
To solve this kind problem, the course instructoruses a template to send specific HTML responses to users depending on their specific requests.
Step One: Create Another HTML Page
We create another HTML page in EJS file. In my HTML page, I just put some diet text and named it as “diet.ejs”.
Step Two: Write The Route Parameter and render the EJS file
In the app.js, I write a route parameter “/wantto/:thing”in the app.get. By following this pattern, users can request any word to replace the “thing” to match the route and get response.
Inside the function, I write res.render(“diet.ejs”)to render the diet HTML page.
Therefore, when I run the app, and request “/wantto/health”, the app send the diet HTML page to me.
Step Three: Add the Template
We create a template by adding an object:res.render(“diet.ejs”, {thingVar: thing}).
In the object, we can put multiple pieces of data that we want to have in the template.
In the template, “thingVar” should be equal to “thing”. So, it will take the value of “thing” and stick it right there.
Then, we go back to diet.ejs file and add a ejs basket after Diet Idea:<%= thingVar %>. This is just a simple JavaScript inside the HTML page.
Then, we run the app. When I request “/wantto/EatLess”, the page shows the “Diet Idea :EatLess”. EatLess is the “thingVar”. You can replace any thing you want by following the certain pattern.
This is very powerful. According to the course, pretty much every app has these dynamic pages. All responses can change depending on what user asked for in specific pieces of date in the request.
网友评论