“res.render"是什么?做,以及 html 文件是什么样的? [英] What does "res.render" do, and what does the html file look like?

查看:70
本文介绍了“res.render"是什么?做,以及 html 文件是什么样的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

res.render 做了什么,html 文件是什么样的?

What does res.render do, and what does the html file look like?

我的最终目标是将文本文件中的任意逗号分隔值加载到 html 文件中(例如).我只能推断出一个视图是 html 文件,回调返回了那个 html 文件.

My end goal is to load arbitrary comma-separated-values from a text file into an html file (for example). I was only able to deduce that a view was the html file, and callback gives that html file back.

这里是文档:http://expressjs.com/api.html#res.render.

现在,根据我发现的一些示例代码的上下文,有一些关于将 ejs(嵌入式 javascript)与 <%%>.

Now, given context from some example code I found, there is something about using ejs (embedded javascript) with <% and %>.

但如果我可以补充一下,我只是不称职还是文档真的很模糊并假设读者无所不知?我怎么能自己解决这个问题?是否有任何官方文档可以让我全面了解用法、优点和缺陷?

But if I may add, am I just incompetent or is the documentation really truly vague and assumes the reader knows everything? How could I have gone about figuring this out on my own? Is there any official documentation so I can gain a full understanding of usage, advantages and pitfalls?

编辑 1

我只想补充一点,我有很多时间学习 node.js.是我还是一般文档真的很模糊?除了像上面那样糟糕的解释,没有参数或返回值的类型规范.

I just want to add that I'm having a heck of a time learning node.js. Is it me or is the general documentation really vague? Aside from lousy explanations like above, there are no type specifications for parameters or return values.

编辑 2

让我在代码上方问你一些更具体的问题.

Let me ask you some more specific questions above the code.

实际的orders.ejs 文件在views/orders.ejs 中.这段代码是怎么引用的?

The actual orders.ejs file is in views/orders.ejs. How does this code refer to it?

HTML 摘录:

<tbody>
  <% for(var i=0; i<orders.length; i++) {%>
     <tr>
       <td><%= orders[i].id %></td>
       <td><%= orders[i].amount %></td>
       <td><%= orders[i].time %></td>
     </tr>
     <% } %>

还有js.请参阅/订单:

And the js. Please see /orders:

  // Define routes for simple SSJS web app. 
// Writes Coinbase orders to database.
var async   = require('async')
  , express = require('express')
  , fs      = require('fs')
  , http    = require('http')
  , https   = require('https')
  , db      = require('./models');

var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 8080);

// Render homepage (note trailing slash): example.com/
app.get('/', function(request, response) {
  var data = fs.readFileSync('index.html').toString();
  response.send(data);
});

// Render example.com/orders
app.get('/orders', function(request, response) {
  global.db.Order.findAll().success(function(orders) {
    var orders_json = [];
    orders.forEach(function(order) {
      orders_json.push({id: order.coinbase_id, amount: order.amount, time: order.time});
    });
    // Uses views/orders.ejs
    response.render("orders", {orders: orders_json});
  }).error(function(err) {
    console.log(err);
    response.send("error retrieving orders");
  });
});

// Hit this URL while on example.com/orders to refresh
app.get('/refresh_orders', function(request, response) {
  https.get("https://coinbase.com/api/v1/orders?api_key=" + process.env.COINBASE_API_KEY, function(res) {
    var body = '';
    res.on('data', function(chunk) {body += chunk;});
    res.on('end', function() {
      try {
        var orders_json = JSON.parse(body);
        if (orders_json.error) {
          response.send(orders_json.error);
          return;
        }
        // add each order asynchronously
        async.forEach(orders_json.orders, addOrder, function(err) {
          if (err) {
            console.log(err);
            response.send("error adding orders");
          } else {
            // orders added successfully
            response.redirect("/orders");
          }
        });
      } catch (error) {
        console.log(error);
        response.send("error parsing json");
      }
    });

    res.on('error', function(e) {
      console.log(e);
      response.send("error syncing orders");
    });
  });

});

// sync the database and start the server
db.sequelize.sync().complete(function(err) {
  if (err) {
    throw err;
  } else {
    http.createServer(app).listen(app.get('port'), function() {
      console.log("Listening on " + app.get('port'));
    });
  }
});

// add order to the database if it doesn't already exist
var addOrder = function(order_obj, callback) {
  var order = order_obj.order; // order json from coinbase
  if (order.status != "completed") {
    // only add completed orders
    callback();
  } else {
    var Order = global.db.Order;
    // find if order has already been added to our database
    Order.find({where: {coinbase_id: order.id}}).success(function(order_instance) {
      if (order_instance) {
        // order already exists, do nothing
        callback();
      } else {
        // build instance and save
          var new_order_instance = Order.build({
          coinbase_id: order.id,
          amount: order.total_btc.cents / 100000000, // convert satoshis to BTC
          time: order.created_at
        });
          new_order_instance.save().success(function() {
          callback();
        }).error(function(err) {
          callback(err);
        });
      }
    });
  }
};

推荐答案

res.render 做了什么,html 文件是什么样的?

What does res.render do and what does the html file look like?

res.render() 函数编译你的模板(请不要使用 ejs),在那里插入局部变量,并从这两个东西中创建 html 输出.

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.

回答编辑 2 部分.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

所以,模板路径是 views/(第一部分)+ orders(第二部分)+ .ejs(第三部分)=== views/orders.ejs

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs

无论如何,express.js 文档非常适合它的功能.这是 API 参考,不是如何使用 node.js"的书.

Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

这篇关于“res.render"是什么?做,以及 html 文件是什么样的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆