Include HTML blocks Using node.js

前端 未结 5 632
生来不讨喜
生来不讨喜 2021-02-04 09:01

This is what I want but probably can\'t have:

Using node.js and express and maybe ejs, I would like to, while writing a regular HTML file in my client dir, server-side-i

5条回答
  •  时光取名叫无心
    2021-02-04 09:18

    OK I got it...

    server.js

     var express =      require('express');
     var server  =      express();
     var ejs = require('ejs'); 
     ejs.open = '{{'; 
     ejs.close = '}}';
    
    
     var oneDay = 86400000;
     server.use(express.compress());
    
     server.configure(function(){
       server.set("view options", {layout: false});  
       server.engine('html', require('ejs').renderFile); 
       server.use(server.router);
       server.set('view engine', 'html');
       server.set('views', __dirname + "/www");
     });
    
    
     server.all("*", function(req, res, next) {
         var request = req.params[0];
    
             if((request.substr(0, 1) === "/")&&(request.substr(request.length - 4) === "html")) {
             request = request.substr(1);
             res.render(request);
         } else {
             next();
         }
    
     });
    
     server.use(express.static(__dirname + '/www', { maxAge: oneDay }));
    
     server.listen(process.env.PORT || 8080);
    

    and in /www I have the following .html files:

    index.html

          {{include head.html}}
     {{include header.html}}
    
     

    Hello world!

    {{include footer.html}}

    head.html

     
     
     
     
       
         
             
             
             
             
             
    
             {{include include.css.html}}
    
             
         
              
    

    include_css.html

          
          
          
          
    

    header.html

     

    HEADER

    footer.html

             

    FOOTER

    It all comes through, even includes in includes and static content. It is all performed on html files, and in a context that feel like vanilla web authoring.

    ++++Oops+++++ Well I almost all of it. I forgot that I also wanted to be able to pass variables into the include from the templates. I haven't tried that yet... any ideas?

    ++++Update+++++

    Ok I figured it out.

    This discussion made it clear, i guess i just didn't know enough about how ejs worked.

    I have changed index.html to begin with variable declarations:

     {{
        var pageTitle = 'Project Page';
        var projectName = 'Project Title';
     }}
    

    and then you can call these variables from within the includes, no matter how deeply they are nested.

    So for instance, index.html includes start.html which includes header.html. Within header .html I can call {{= projectName}} within the header even though it was declared inside index.html.

    I have put the whole thing on github.

提交回复
热议问题