Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a variable to inline javascript using EJS templating engine?

I've created a html list of buttons/text from an array called items in an .EJS template. How do I pass the specific item's id (item.id) to the button's function so I can send the right data to my api? Thanks.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Menu</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script type="text/javascript">

    function print(id) {
        $.ajax({
          url: "https://www.example.com/api/1/print",
          type: "POST",
          data: {
            "item_id": id
          },
          dataType: "json",
          success: function (result) {
            alert(result);
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
          }
        });
      };
    </script>
  </head>
  <body>
    <h2>Menu</h2>
    <ul>
        <% for(item of items) { %>
          <li>
            <button onclick="print(item.id)">PRINT</button>
            <%= item.name %> - <%= item.id %>
          </li>
        <% } %>
    </ul>
  </body>
</html>
like image 493
supster Avatar asked Feb 17 '16 01:02

supster


People also ask

How do I pass a variable from EJS to JavaScript?

var express = require('express'); var app = express(); var myVar = 1; In the ejs file , where I want to use that variable inside a few if statements ,I have to declare it again in order to be able to use it. ejs file: var myVar = 1; if ( my Var ) ....

How do I declare a variable in EJS file?

A variable declaration starts with the keyword var followed by the variable name, e.g. : var myVariable; The variable declaration ends with a semi-colon. The names of the variables in EJS-templates are case-sensitive: myVariable and myvariable are different variables.


1 Answers

<button onclick="print('<%= item.id %>')">PRINT</button>

is how you would do it in every templating language I have used. After looking at the docs, it appears EJS is the same

like image 117
thedarklord47 Avatar answered Oct 06 '22 00:10

thedarklord47