Dynamic html generation

Hey!
I would like to generate my html file according to what the input data contains

For that I created a function to create the html code that I need. My goal is to then integrate it into the body of my html code


  let htmlContent = '';
  let surveyData = {{ $json.body.surveyData }}
  function generateHTMLFromSurveyData(surveyData) {

  surveyData.forEach(item => {
      switch (item.type) {
          case 'text':
          case 'comment':
              htmlContent += `
              <div class="question-block">
                  <div class="question-label">${item.title}</div>
                  <div class="question-value">${item.value}</div>
              </div>`;
              break;

          case 'matrixdynamic':
              if (Array.isArray(item.value)) {
                  htmlContent += `
                  <div class="question-block">
                      <div class="question-label">${item.title}</div>
                      <div class="question-value">
                          <table class="response-table">
                              <tr>
                                  ${Object.keys(item.value[0]).map(key => `<th>${key}</th>`).join('')}
                              </tr>`;
                  item.value.forEach(row => {
                      htmlContent += `<tr>${Object.values(row).map(val => `<td>${val}</td>`).join('')}</tr>`;
                  });
                  htmlContent += `
                          </table>
                      </div>
                  </div>`;
              }
              break;
       (...)
    });
    return htmlContent;
  }

  generateHTMLFromSurveyData(surveyData);
  

(in script tags)

As input I transmit an array containing several objects themselves composed of 4 parameters. type, name, value (the last is useless)

My goal is therefore to make the html file generate itself with its information thanks to the generateHTMLFromSurveyData function after that I would just have to integrate htmlContent into the body.

However I do not know how to execute my function in my script and how to use the result in my html

Did I make a mistake? :grimacing:

It looks like your topic is missing some important information. Could you provide the following if applicable.

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

Hey @Alister_Flandrinck,

you need to put that function into a code node. Here’s how that would look:

best,

Jon


automaze.me

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.