简体   繁体   English

渲染 HandleBars 模板节点/Express 后执行 Javascript

[英]Execute Javascript after Rendering HandleBars Template Node/Express

i have a node application and i am trying to render a jquery datatable after the data has loaded, so far i have been able to populate the table with the data but i am trying to initialize the datatable and its not working..我有一个节点应用程序,我正在尝试在加载数据后呈现 jquery 数据表,到目前为止,我已经能够用数据填充表,但我正在尝试初始化数据表并且它不工作..

here i rander the template我在这里对模板进行排序

router.get('/user/operations', (req, res)=>{
    var data;

    const data = axios.get('http://localhost:8945/api/users/operations')
    .then(function (response) {
       data = response.operations;  //i retrieve the data from the api
     })
    .catch(function (error) {
       console.log(error);
     });
    
    res.render('pages/tables', {
        pgtitle:'All User Operations..',
        usrData:data            // i pass the data to the template and successfully render the table
    });          
})

i rendered the view properly using HandleBars Template Engine, but the datatable doesn't initialize after the view has been rendered, the table has an id of UsersDataTB but if it was in jquery, i would have called the script below immediate after the rendering process to initialize the datatable.我使用 HandleBars 模板引擎正确渲染了视图,但是在渲染视图后数据表没有初始化,表的 id 为UsersDataTB但如果它在 jquery 中,我会在渲染过程之后立即调用下面的脚本初始化数据表。

 $('#UsersDataTB').DataTable( {
    responsive: true,
    pagingType: "full_numbers"
 });

but now i don't know where to run a script after the view-template has been rendered using HandleBars in Express, please how do i go about it,但是现在我不知道在使用 Express 中的 HandleBars 呈现视图模板后在哪里运行脚本,请问我如何 go 关于它,

Asides this, every other feature is working as expected.除此之外,所有其他功能都按预期工作。

Looking at your express code I would think that the view will be rendered first before your axios request has finished.查看您的快速代码,我认为该视图将在您的axios请求完成之前首先呈现。 That is because of the asynchronous nature of the request Axios makes.这是因为 Axios 发出的请求的异步性质。

To make sure that you render your template after the data has been fetched use async / await or render your template in the .then() callback after the request has been made.为确保在获取数据呈现模板,请使用async / await或在发出请求后在.then()回调中呈现模板。

router.get('/user/operations', async (req, res) => {

  const response = await axios.get('http://localhost:8945/api/users/operations');
  const { operations } = response;

  res.render('pages/tables', {
    pgtitle: 'All User Operations..',
    usrData: operations
  }
       
})

If the 'pages/tables' template contains a script with jQuery, the DataTable plugin and your initialization code then that script should run whenever the page has been loaded.如果'pages/tables'模板包含带有 jQuery 的脚本、DataTable 插件和您的初始化代码,则该脚本应该在页面加载后运行。

So if your script contains:因此,如果您的脚本包含:

$('#UsersDataTB').DataTable({
  responsive: true,
  pagingType: "full_numbers"
});

Then it should look for the id="UsersDataTB" element and create the data table.然后它应该查找id="UsersDataTB"元素并创建数据表。 This is initializing the table.初始化表。 But I assume that your table is empty because there is no data.但我假设你的表是空的,因为没有数据。

Otherwise check your console for any error messages and inspect the data table element to see if there are any signs that the initialization went wrong.否则,请检查您的控制台是否有任何错误消息并检查数据表元素以查看是否有任何迹象表明初始化出错。


Edit编辑

In your Handlebars template make sure that your usrData is an array with object that can be looped over to make sure that your template renders a table with multiple rows and cells.在您的 Handlebars 模板中,确保您的usrData是一个包含 object 的数组,可以循环该数组以确保您的模板呈现一个包含多行和单元格的表格。 And then initialize it with the script after it.然后用它后面的脚本初始化它。

<!DOCTYPE html>
<html>
  <head>
    <title>Example template</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />  
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
  </head>
  <body>

    <table id="UsersDataTB">
      <tbody>
        {{#each usrData}}
          <tr>
            <td>{{@key}}</td>
            <td>{{this}}</td>
          </tr>
        {{/each}}
      </tbody>
    </table>
  
    <script src="//code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
    <script>
      $('#UsersDataTB').DataTable( {
        responsive: true,
        pagingType: "full_numbers"
      });
    </script>
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM