I'm wondering about getting variables from the Express backend into the JS part of a website. I find myself doing the following a lot:
- Pass some variable I want to use into res.render
- Put the variable into the HTML as an invisible element with the template engine, ex. in EJS something like
<span id="username" style="display: none;"><%= user.username %></span>
- Get the variable out in the JS with JQuery, ex:
const username = $("#username").text();
But I am wondering if there is a better way...I mean you can't just put anything into the HTML, and I'd prefer to put less just in case...
For example I was making a study course and I wanted to make one call to the DB to get lesson content. But I don't want to put all the lesson content on the page in a hidden element, and I don't want to query the DB for every question. And I don't want to reload the page for every question either, so I'd like to use JS to change the questions...is there some design pattern or common solution for this situation?
CodePudding user response:
I mean you can't just put anything into the HTML
This is debatable. It depends on how much dynamic content there is; if there isn't hundreds of kilobytes worth or more, I wouldn't find it strange if some developer in that situation decided to embed all the data in one page, and in the JavaScript, extract what they need from it when required.
Still, if that isn't an option, or if that doesn't seem elegant, there are 2 approaches you could consider:
Put all the data you need for a page in a single element, rather than creating an element for each different piece of data. For example, say you constructed a
dataForPage
object that contained the username and whatever else is needed, and then interpolated that into the page once.<script type="application-json" > <%= JSON.stringify(dataForPage %> </script>
and extract it with
const dataForPageText = document.querySelector('.dataForPage').textContent; const { username, /* other desired properties */ } = JSON.parse(dataForPageText);
Or, make a client-side request for the same chunk of all data that the page needs. This will mean that instead of interpolating the data through EJS, you'll need to set up an API route on your server. This is a very common approach too.
And I don't want to reload the page for every question either
Sure, there's no need to, if you build a single-page application of sorts for the questions.