Home > database >  Render a Web JS Variable within an ExpressJS statement
Render a Web JS Variable within an ExpressJS statement

Time:08-24

I am attempting to render the variable cat which is a string within an ExpressJS statement AND a script tag.

Here is my code:

<script>
            function detectChange() {
                var place;
                cat = document.getElementById("catType").value; // coollink
                type = document.getElementById("appType").value;
                
                if(type == "application") {
                    place = `<%= certain.categories.find(o => o.link == cat).placeholder %>`;
                } else {
                    place = 'Topic description...';
                };
                document.getElementsByName('description')[1].innerHTML = place;
            };
</script>

The specific part I have a problem with is:

 place = `<%= certain.categories.find(o => o.link == cat).placeholder %>`;

I want to display cat, which is a WebJS Variable (that for now has a value of coollink) inside of my ExpressJS tags <%= coollink %> however I cannot seem to display it without it erroring and telling me it has an error with compiling it.

It works just fine if I change it to say

place = `<%= certain.categories.find(o => o.link == 'coollink').placeholder %>`;

but then it's not dynamic, and it needs to be dynamic for this project.

CodePudding user response:

You can't do this.

The code inside <%= %> runs on the server side, the cat variable doesn't even exist yet.

What <%= %> do is place any string in this place. It doesn't even know it's a script.

The best you can do is:

<%= certain.categories %>.find(o => o.link == cat).placeholder

But it will expose all categories to the user

  • Related