0

I am developing a website with express.js, and I would like to know how to export a variable in javascript from an ejs file to a js file.

ejs file :

<div class="select">
  <select id="selection_channel">

<% 
let channelText = guild.channels.cache.filter(channel => channel.type == 'text');

channelText.forEach((channel)=>{ 
  
  %>
 <option value="<% channel.id %>">#<%= channel.name %></option>

<% }); %>
<p></p>
<script type="text/javascript" src="../js/submit.js"></script>

</select>
</div>

I would like to export the strUser variable to a my js folder.

My js file :

    // Settings endpoint.
    app.post("/dashboard/:guildID", checkAuth, async (req, res) => {
        // We validate the request, check if guild exists, member is in guild and if member has minimum permissions, if not, we redirect it back.
        const guild = client.guilds.cache.get(req.params.guildID);
        if (!guild) return res.redirect("/dashboard");
        const member = guild.members.cache.get(req.user.id);
        if (!member) return res.redirect("/dashboard");
        if (!member.permissions.has("MANAGE_GUILD")) return res.redirect("/dashboard");
        // We retrive the settings stored for this guild.
        var storedSettings = await GuildSettings.findOne({ gid: guild.id });
        if (!storedSettings) {
          // If there are no settings stored for this guild, we create them and try to retrive them again.
          const newSettings = new GuildSettings({
            gid: guild.id
          });
          await newSettings.save().catch(()=>{});
          storedSettings = await GuildSettings.findOne({ gid: guild.id });
        }
        //var strUser = require('./templates/settings.ejs')
        // We set the prefix of the server settings to the one that was sent in request from the form.
        storedSettings.prefix = req.strUser  //req.body.prefix
        console.log(req.body.strUser)
        // We save the settings.
        await storedSettings.save().catch(() => {});

        // We render the template with an alert text which confirms that settings have been saved.
        renderTemplate(res, req, "settings.ejs", { guild, settings: storedSettings, alert: "Changement effectué avec succès." });
    });
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

You can attach it to the window object

window.usrString = userString;
Bogdan Veliscu
  • 641
  • 6
  • 11
  • I see, but how to use window.strUsr in js file? Because in this case it tells me that window is not defined. –  Aug 10 '20 at 07:56
  • That won’t work. The question is asking how to pass a variable from *server-side* EJS to client-side JS. The `window` object of the browser isn’t available in the JS engine running on the server. – Quentin Aug 10 '20 at 08:12
  • Yes it does not work for me indeed –  Aug 10 '20 at 08:17