0

I have a route for different pages of store profiles in my Node app. Been googling, and I know I can edit the parameters, but I have absolutely no idea how to change the content (loading with React) based on name. I'm just using res.render() to render the specific page.

For example, https://www.instagram.com/adidas shows different content than https://www.instagram.com/nike however, they have the same HTML structure and base profile HTML. It's just the content that is different!

Right now, I just have an store.ejs that is the html structure of each profile.

What's an example for how to change and load content based on the name/id?

4
  • React can be rendered to strong or static markup on server so you may not even need ejs. Commented Dec 23, 2016 at 0:16
  • @WalkerRandolphSmith am I not required to use jade or ejs in an express app? Commented Dec 23, 2016 at 0:21
  • No you are not. Commented Dec 23, 2016 at 0:33
  • You can use facebook.github.io/react/docs/react-dom-server.html with express. Commented Dec 23, 2016 at 0:36

1 Answer 1

2

Route parameters is probably what you're looking for.

app.get('/:name', (request, response) => {
  let locals = {
    name: request.params.name,
    foo: 'bar'
  };

  res.render('store.ejs', locals);
});

The local variables can be referenced within your template file.

 <h1>Hello <%= name %></h1>
 <button><%= foo %></button>

Then navigating to /rohit is going to render a page that contains the following markup.

 <h1>Hello rohit</h1>
 <button>bar</button>

That said, there are many other ways to build application routes, so it's definitely worth reading the routing docs.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Dan. I was able to get that small example to work and went through the documentation. I was wondering, how exactly does this play out in a larger more complex example. Do I need conditional logic to read from <%= name %> json file? How exactly do I deal with different large sets of content?
That really comes down to the template language you decide to use (e.g. ejs, pug, ...). I'd recommend finding some express applications and reading through their source code to get a feel for managing routes/views.
Also remember that you can define as many template files as you need, and you can make your application's routing as complex as is necessary, exposing whichever local variables you want when you render them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.