0

I would like to know how to pass ejs var in a function in javascript

index.ejs
 <%- include('header', {trans: text}) %>

//header.ejs
<% var lang=<%=lang%> %>

    <li class="nav-item">
        <a class="nav-link" href="javascript:" onclick="redirection(lang)">contact</a> // pass the var in function
    </li>

//help.js

    function redirection(val){
        console.log(val);
    }

1 Answer 1

1

Keep in mind that your EJS program and your client-side JS program are two different programs (and generally run on two different computers).

You need to put the data somewhere it can be read by the client-side JS program. For example, a data attribute.

Then the client-side JS program needs to read it.


Aside: href="javascript:" is not a useful URL to visit. This is a strong clue that you shouldn't be using a link. I'll use a button for the rest of this example.

Aside: Event handlers are better bound with JavaScript rather than HTML.


function redirection(event) {
  const button = event.currentTarget;
  const lang = button.dataset.lang;
  console.log(lang);
}

document.querySelector("button").addEventListener("click", redirection);
<button data-lang="<%= lang %>" type="button" class="nav-link">
      contact
</button>

Note in this example the EJS won't run because I have no server to run it on. You can see the EJS source code logged in the demo instead.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.