Programing

Jade 대신 Express에서 HTML 사용

lottogame 2020. 8. 23. 09:38
반응형

Jade 대신 Express에서 HTML 사용


Node.JS와 함께 Express를 사용하는 동안 Jade를 제거하는 방법은 무엇입니까? 평범한 HTML을 사용하고 싶습니다. 다른 기사에서는 사람들이 현재 최신 버전에서 사용되지 않는 app.register ()를 권장하는 것을 보았습니다.


다음과 같이 할 수 있습니다.

  1. ejs 설치 :

    npm install ejs
    
  2. app.js의 템플릿 엔진을 ejs로 설정

    // app.js
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    
  3. 이제 경로 파일에서 템플릿 변수를 할당 할 수 있습니다.

    // ./routes/index.js
    exports.index = function(req, res){
    res.render('index', { title: 'ejs' });};
    
  4. 그런 다음 / views 디렉토리에 html보기를 만들 수 있습니다.


Jade는 html 입력도 허용합니다.
순수한 HTML 제출을 시작하려면 줄 끝에 점을 추가하십시오.
그것이 당신을 위해 속임수를 쓰면 다음을 시도하십시오.

doctype html              
html. // THAT DOT
    <body>     
        <div>Hello, yes this is dog</div>
    </body>

추신-HTML을 닫을 필요가 없습니다.이 작업은 Jade가 자동으로 수행합니다.


Express 3부터는 간단히 사용할 수 있습니다. response.sendFile

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});)

에서 공식 특급 API 참조 :

res.sendfile(path, [options], [fn]])

주어진 경로에서 파일을 전송하십시오.

파일 이름 확장자에 따라 Content-Type 응답 헤더 필드의 기본값을 자동으로 설정합니다. 콜백 fn(err)은 전송이 완료되거나 오류가 발생할 때 호출됩니다.

경고

res.sendFilehttp 캐시 헤더를 통해 클라이언트 측 캐시를 제공하지만 서버 측에서 파일 내용을 캐시하지 않습니다. 위의 코드는 각 요청에서 디스크에 도달합니다 .


제 생각에는 html 파일을 읽기 위해 ejs와 같은 큰 것을 사용하는 것은 약간 무겁습니다. 매우 간단한 html 파일 용 템플릿 엔진을 방금 작성했습니다. 파일은 다음과 같습니다.

var fs = require('fs');
module.exports = function(path, options, fn){
    var cacheLocation = path + ':html';
    if(typeof module.exports.cache[cacheLocation] === "string"){
        return fn(null, module.exports.cache[cacheLocation]);
    }
    fs.readFile(path, 'utf8', function(err, data){
        if(err) { return fn(err); }
        return fn(null, module.exports.cache[cacheLocation] = data);
    });
}
module.exports.cache = {};

나는 내 htmlEngine을 불렀고 그것을 사용하는 방법은 단순히 다음과 같이 말하는 것입니다.

app.engine('html', require('./htmlEngine'));
app.set('view engine', 'html');

app.register()감가 상각되지 않았 app.engine()으며 Express 3 가 템플릿 엔진 처리 방식을 변경 한 이후 로 이름이 변경되었습니다 .

Express 2.x template engine compatibility required the following module export:

exports.compile = function(templateString, options) {
    return a Function;
};

Express 3.x template engines should export the following:

exports.__express = function(filename, options, callback) {
  callback(err, string);
};

If a template engine does not expose this method, you're not out of luck, the app.engine() method allows you to map any function to an extension. Suppose you had a markdown library and wanted to render .md files, but this library did not support Express, your app.engine() call may look something like this:

var markdown = require('some-markdown-library');
var fs = require('fs');

app.engine('md', function(path, options, fn){
  fs.readFile(path, 'utf8', function(err, str){
    if (err) return fn(err);
    str = markdown.parse(str).toString();
    fn(null, str);
  });
});

If you're looking for a templating engine that lets you use 'plain' HTML, I recommend doT because it is extremely fast.

Of course, keep in mind that the Express 3 view model leaves view caching up to you (or your templating engine). In a production environment, you probably want to cache your views in memory so that you aren't doing disk I/O on every request.


You can use EJS with express which templates are HTML but support variables. Here is a good tutorial in how to use EJS in express.

http://robdodson.me/blog/2012/05/31/how-to-use-ejs-in-express/


To make the render engine accept html instead of jade you can follow the following steps;

  1. Install consolidate and swig to your directory.

     npm install consolidate
     npm install swig
    
  2. add following lines to your app.js file

    var cons = require('consolidate');
    
    // view engine setup
    app.engine('html', cons.swig)
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', ‘html');
    
  3. add your view templates as .html inside “views” folder. Restart you node server and start the app in the browser.

Though this will render html without any issue, I would recommend you to use JADE by learning it. Jade is an amazing template engine and learning this will help you achieve better design & scalability.


Well, it sounds like you want to serve static files. And there is a page for that http://expressjs.com/en/starter/static-files.html

Bizarre that nobody is linking to the documentation.


first check the compatibility version of template engine by using below line

express -h

then you have to use no view from the list.select no view

express --no-view myapp

now you can use your all html,css,js and images in public folder.


since Jade supports HTML, if you just want to have .html ext, you can do this

// app.js
app.engine('html', require('jade').renderFile);
app.set('view engine', 'html');

then you just change file in views from jade to html.


You can also directly include your html file into your jade file

include ../../public/index.html

Original answer: Express Generator Without Jade


Considering you have your routes already defined or do know how to do it.

app.get('*', function(req, res){
    res.sendfile('path/to/your/html/file.html');
});

NOTE: this route has to be placed after all the others since * accepts everything.


If you want to use plain html in nodeJS, without using jade.. or whatever:

var html = '<div>'
    + 'hello'
  + '</div>';

Personnaly i'm doing fine with that.

The advantage is simplicity when control. You can use some tricks, like '<p>' + (name || '') + '</p>', ternary .. etc

If you want an indented code in the browser, you can do:

+ 'ok \
  my friend \
  sldkfjlsdkjf';

and use \t or \n at will. But i prefer without, plus it is faster.

참고URL : https://stackoverflow.com/questions/11495595/using-html-in-express-instead-of-jade

반응형