whitespaces when adding partial template using EJS

ⅰ亾dé卋堺 提交于 2019-12-08 04:04:12

问题


I am using SailsJS with EJS engine.

When I add partials using <% include partials/template.ejs %> or <% partial('partials/template.ejs') in the layout file, I get whitespaces before the compiled HTML code (template.ejs).

Note that when I copy paste the template.ejs content in the layout (not using include/partials) the whitespaces are gone.

See images below:

1st part: code.

2nd part: chrome DOM.

3rd part: whitespace element inspection (DOM properties)


回答1:


I have faced the same problem. What I did was very simple.

Go to ejs module index.js file. Find partial function. Find this part of code:

var source = options.cache
? cache[key] || (cache[key] = fs.readFileSync(file, 'utf8'))
: fs.readFileSync(file, 'utf8'); 

and replace it with

var source = options.cache
? cache[key] || (cache[key] = fs.readFileSync(file, 'utf8').trim())
: fs.readFileSync(file, 'utf8').trim();

So, what I did is just used trim() java script function.

Hope it'll be helpful.




回答2:


I got the same problem when using ejs render. Some white space was included in my code, causing positionnement problems.

I looked everwhere on the internet, and finally build my own solution :

    var clean= function(selecteur) {
        var save=new Array();
        selecteur.children().each(function() {
            save.push(this);
        });
        selecteur.empty();
        for(i in save) {
            selecteur.append(save[i]);
        }
    };

This function can be called on any jquery selector container that need to be cleaned from any whitespace. It works basically by saving all your contents in a local variable, emptying your container, then, adding your saved contents.




回答3:


I encountered the same thing and at least in my case this was due to the EJS partial function using

fs.readFileSync(file, 'utf8')

which according to

https://github.com/nodejs/node-v0.x-archive/issues/1918

does not remove the UTF-8 BOM. While it would be nice if the EJS engine stripped away the BOM for us, saving the partial files in UTF-8 without the BOM solved my problem.



来源:https://stackoverflow.com/questions/23620128/whitespaces-when-adding-partial-template-using-ejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!