Is it possible to invoke a Node.js function within PugJS?

I am looking to implement a clickable button in PugJS that triggers JavaScript code within Node.js.

views/index.pug

doctype html
html
  head
    title #{title}
    link(rel='stylesheet', href='/css/style.css')
    meta(name="viewport" content="width=device-width, initial-scale=1")
  body
    main
      block header
        header.header
          h1 #{title}
      block content
  button(type='submit' onClick='foo();') Click

index.js

var http = require('http'),
    fs = require('fs'),
    util = require('util'),
    express = require('express'),
    pug = require('pug');

var app = express();

app.set('view engine', 'pug');

var foo = function() {
    console.log("foobar");
};

app.get('/', (req, res) => {
  res.render('index', {title: "Awesome name", func: foo});
});

app.post('/', function(req, res) {
  console.log(req.body);
  res.send(200);

  // sending a response does not pause the function
  foo();
});

app.use(express.static(__dirname + '/public'));

const server = app.listen(7000, () => {
  console.log(`Express running → PORT ${server.address().port}`);
});

Directly referencing `foo` results in "undefined" as the function is undefined in scope. Attempting to reference `func` with `#{func}` inside index.pug leads to errors. How can I correctly reference the JavaScript function within Node.js from a button created in PugJS?

Answer №1

Utilizing a template engine to execute code on the server is not advisable due to the significant security risks involved. Template engines are primarily designed for rendering data server-side. In your particular scenario, the foo() function should perform necessary operations and then pass the resulting data to your pug template when you render it by using something like

res.render("mytemplate",{foodataL:data})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating a field within an array of objects in Node.js and MongoDB: A step-by-step guide

My main objective is to change the value of the field "done" to "true" I am currently working on a project using nodejs Below is the document for reference: { "_id" : ObjectId("5a730e55114dbc2a0455c630"), "email" : "<a href="/cdn-cgi/l/email-protect ...

Test the file upload functionality of a Node Js application by simulating the process using Chai

My API testing involves receiving a file as input. I have successfully used the attach() function for this purpose. To cover all scenarios, I anticipate using around 20 different input files. Rather than storing these 20 files individually, my idea is to c ...

When using jQuery Ajax, only pass the query string if it is defined and not empty

Using jquery and ajax to communicate with a CMS API, I am constructing a query string to fetch data: region = typeof region !== 'undefined' ? 'region='+region : ''; centre = typeof centre !== 'undefined' ? 'cen ...

What is the best way to configure Winston with Webpack?

I'm working on an electron application that utilizes node.js and I want to integrate the Winston logging library. After adding Winston to my package.json file, I encountered warnings from the colors.js dependency when running the webpack build command ...

Exploring Symfony2: Enhancing user experience with dynamic form submission and dropdown menu updates

Starting from the beginning. I have a tab-panned layout with links. Upon clicking a link, a drop-down checkbox form is injected directly into the HTML through $(".dropdown-toggle").click(function() { var projectId = $("#permission-form").attr("data-p ...

howler.js resumes playing sprite sound after being paused

I have been working on setting up an audio sprite using Howler.js. The basic functionality of the sprite is working well, but I am facing an issue when trying to resume playback after pausing a sprite. When I call play(), it does not work as expected. sou ...

What is the best way to integrate Bootstrap 5 with Next.js?

After adding Bootstrap to my project with npm install bootstrap, I included the style in /pages/_app.js like this: import 'bootstrap/dist/css/bootstrap.css'; export default function App({ Component, pageProps }) { return <Component {...pag ...

Conceal a form field depending on the data retrieved from a database in PHP

I need assistance with hiding an input field based on the chosen value from a dropdown. There are two values, stone1 and stone2, that are automatically populated from a database. My goal is to hide the "karat" input field if stone1 is selected, hide the "c ...

Utilizing an AngularJS factory to invoke a function within another function

I am encountering an issue with my AngularJS factory that consists of multiple functions. My goal is to call one of the functions from within another function, as demonstrated in the code snippet below: .factory("AppStart", function($cordovaSQLite) { r ...

I seem to be struggling with hiding/showing a div element. Can you figure

I am in the process of creating a gallery that will display a div with images when a button is clicked. The issue I am facing is that when I have two buttons, only the last images are clickable. It's a bit difficult to explain, but you can see it in ...

Why doesn't Material-UI seem to understand the theme.spacing function?

Issue with Material-UI's theme.spacing function I've encountered a problem while using Material-UI's theme.spacing function in a React application. It seems that the spacing function is not being recognized. The Javascript error message st ...

Can you help me navigate through the router dom v6 to match product IDs from the API?

How do I display a specific product when it's clicked on based on its id from a Django Rest Framework API? I was previously using match from React Router DOM v5, but I'm not sure how to achieve the same functionality since match doesn't exis ...

Create a unique component in ReactJS with the react-google-maps package to enhance your user interface

I would like to integrate a custom marker component into the map, but I have observed that using react-google-maps/api does not support rendering custom components. To illustrate this, here is an example of the code I used: const CustomMarker = ({ text }) ...

Is there a way for me to handle state changes within a controller for nested views?

Currently, I am attempting to execute a resolve function upon a state change in order to retrieve data that I need to inject into a controller that utilizes "multiple" views. The rationale behind having nested views is due to the presence of a template/app ...

Using two parameters in a function in R

I've been exploring functions to deepen my understanding, and came across an example online that I'm having trouble with. The equation I'm trying to solve involves variables a, v, and r. Specifically, I want to calculate a when v=10 and r=3. ...

Improved Approach for Replacing if/else Statements

I'm looking to streamline the controller used in my SQL command for filtering records based on specific criteria. The current approach below is functional, but not without its limitations. One major issue is scalability - adding more criteria in the f ...

Looking to display a single Angular component with varying data? I have a component in Angular that dynamically renders content based on the specific URL path

I have a component that dynamically renders data based on the URL '/lp/:pageId'. The :pageId parameter is used to fetch data from the server in the ngOnInit() lifecycle hook. ngOnInit(){ this.apiHelper.getData(this.route.snapshot.params.pageId) ...

What steps should be followed to upgrade node.js from version 5.9.1 to 6.14.0 in a secure manner

Our current node version is 5.9.1 and we are looking to transition to a newer version that supports ES6. Specifically, I am aiming to upgrade to at least version 6.14.0, which is known to support almost all of the ES6 features. However, I must admit that ...

"Is it possible to generate a Keystone list object without the need for an

Can a Keystone List (Model) item be created without the initial dialog? I am looking to create the item directly on the detail page, with required fields like Files and TextArray that would not function properly in a dialog. I have attempted to set init ...

How can I trigger my function in jQuery after inputting into the jQuery text field?

Looking for advice on implementing a function in jQuery for a text field that is not working as expected. The code works fine when creating a text field in HTML, but encounters issues with the jQuery text field. <!DOCTYPE html> <html> <body ...