0

I'm using Node.JS and EJS (if it matters) and I'm wondering how I can render a dynamically created HTML file within a page. For example, there is my views folder which contains all the files that is in my website, and there is also a folder in there called User1 which belongs to the currently logged in user, and in that folder User1 is an HTML file he has created before. And when he vists his dashboard, in an iFrame (or however) it will render the file inside the folder User1.

If it helps, I can send the file content as a variable from my back end to the front end, but it is just raw HTML code.

Hello Mellow
  • 169
  • 2
  • 15
  • Full html? header navbar etc everything each time? – SanSolo Dec 24 '18 at 03:35
  • You can do it. Not going to discuss should or shouldn't. You pass html as data in Node.js, in the front end use special syntax to escape html, so it will render as html. Refer to this question on [how to escape html in ejs](https://stackoverflow.com/questions/16183748/how-to-escape-html-in-node-js-ejs-view). Also, iFrame is not necessary – SanSolo Dec 24 '18 at 03:38
  • @SanSolo Just after trying that method out I found out how to render it using an iframe (by using the srcdoc) but what ends up happening is the [EJS I've written just gets pasted as plain tex](https://i.gyazo.com/6368c0bf56b0c4adb5b4e281244e41b5.png)t, is there any way to fix this? (Same thing happens if I do it how you mentioned, the EJS gets posted as plain text) – Hello Mellow Dec 24 '18 at 03:45

1 Answers1

0

As my per understanding, you want to combine deferent pages. You need to develop a function that read deferent files and combine them together and send the response to the client. You need to define the content type to 'text/html'.

Sample Functions: Description: 1. Read the main page 2. Read header 3. Read footer 4. Combine the page part 5. Send to the response.

// Main Object
_index = {};

// This object return content of the page
_index.get = function(data, callback) {
    const templateData = {};
    templateData['head.title'] = 'Page Title';
    templateData['head.description'] = 'Description';
    templateData['body.title'] = 'Body Title';
    templateData['body.class'] = 'css-class';

    // Read the main page contant.
    _index.getTemplate('index', templateData, (err, str) => {
        if (!err && str) {
            // Read rest of the page contant and put them together.
            _index.addUniversalTemplate(str, templateData, (err, str) => {
                if ((!err, str)) {
                    callback(200, str, 'html');
                } else {
                    callback(500, undefined, 'html');
                }
            });
        } else {
            callback(500, undefined, 'html');
        }
    });
// callback(undefined, undefined, 'html');
};


_index.getTemplate = (templateName, data, callback) => {
  templateName =
    typeof templateName == 'string' && templateName.length > 0
      ? templateName
      : false;
  if (templateName) {
    const templateDir = path.join(__dirname, './../template/');
    fs.readFile(templateDir + templateName + '.html', 'utf8', (err, str) => {
      if (!err && str && str.length > 0) {
        // Do interpolation on the data
        let finalString = _index.interpolate(str, data);
        callback(false, finalString);
      } else {
        callback('No Template could be found.');
      }
    });
  } else {
    callback('A valid template name was not specified.');
  }
};


// Add the universal header and footer to a string and pass provided data object to the header and footer for interpolation.
_index.addUniversalTemplate = function(str, data, callback) {
  str = typeof str == 'string' && str.length > 0 ? str : '';
  data = typeof data == 'object' && data !== null ? data : {};
  // Get header
  _index.getTemplate('_header', data, (err, headerString) => {
    if (!err && headerString) {
      _index.getTemplate('_footer', data, (err, footerTemplate) => {
        if (!err && footerTemplate) {
          let fullString = headerString + str + footerTemplate;
          callback(false, fullString);
        } else {
          callback('Could not find the footer template');
        }
      });
    } else {
      callback('Could not find the header template.');
    }
  });
};
  • So here "_index.interpolate(str, data);" just updates 'data' with 'str' or anything else is done ? – Vishal-L Dec 24 '18 at 04:12
  • In "_index.interpolate(str, data);" you need to use replace to place data into "str". I left an example of that. – Behrooz Dec 25 '18 at 18:52
  • for (let key in data) { if (data.hasOwnProperty(key) && typeof data[key] == 'string') { let replace = data[key]; let find = {${key}}; str = str.replace(find, replace); } } – Behrooz Dec 25 '18 at 18:54