Calling a javascript function in ejs files

Asked

Viewed 552 times

0

I am trying to create in my js file a function to format a date by changing "-" to "/" and I am using Node.js and express as follows.

function formatDate(str){
    var format = str.toString().replace("-", "/");
    console.log(format);
    return format;
}

This refused.PERIODO_COBRANCA is coming from a json

<td>
   <%= formatDate(refused.PERIODO_COBRANCA) %>
</td>

inserir a descrição da imagem aqui inserir a descrição da imagem aqui inserir a descrição da imagem aqui

  • Voce is sending the function formDate as an object parameter in the method render()?

  • @Cmtecardeal I’m not doing that, I’ve been testing here now this way.

  • @Cmtecardeal, I tested it the way you said, but I couldn’t get to the point of doing it right. I did as follows, res.render (I PUT MY FUNCTION IN HERE). also did res.render(formatDate(str)) calling the function inside the render, but it did not work.

  • Voce placed the function inside the object? like this: res.render('sua_view', { formDate: formDate }; ?

  • Friend you can’t just call backend functions like this... you need to send it somehow to your template. As @Cmtecardeal suggested res.render('./templates/customers/customer', { formDate: formDate })

1 answer

0


It is necessary to pass the function reference to the View context. You can pass the function as a parameter in the same way you send data to the View, for example: res.render('myView', { formatDate }).

Another way is to use the app.locals or res.locals to provide the function within your view. The difference is in the life cycle. The app.locals persists throughout the application throughout its life, already the res.locals persists only during the lifecycle of a Sponse. See an example:

function formatarValor(entrada) {
    return entrada.toUpperCase();
}

// Com a linha abaixo a função "formatarValor" fica disponível dentro da view
app.locals.formatarValor = formatarValor;

app.get('/', (req, res) => {
    var dados = ['valor 1', 'valor 2', 'valor 3', 'valor 4'];
    res.render('myView', { dadosDaView: dados });
});

I wrote a short text about this scenario: https://medium.com/@Marcelo.vismari/nodejs-express-ejs-como-usar-funcoes-durante-renderizacao-f51122e1eaca

  • Thank you very much, I managed to do what I wanted with the help of your post.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.