项目帮助:下划线模板



我有一个项目,需要我使用下划线模板。

应用程序应该从API获取食谱并将其呈现给页面。如果用户喜欢这个食谱,他们将能够保存它以供以后使用。

有谁能告诉我该怎么做吗?我不确定请求是否应该从客户端或服务器完成。此外,我不太确定如何从API (JSON)返回的数据将被呈现到页面。

下面是我在API上使用postman获得的JSON对象:

{"recipe": {
"publisher": "Closet Cooking",
"f2f_url": "http://food2fork.com/view/35171",
"ingredients": [
  "1/4 cup cooked shredded chicken, warm",
  "1 tablespoon hot sauce",
  "1/2 tablespoon mayo (optional)",
  "1 tablespoon carrot, grated",
  "1 tablespoon celery, sliced",
  "1 tablespoon green or red onion, sliced or diced",
  "1 tablespoon blue cheese, room temperature, crumbled",
  "1/2 cup cheddar cheese, room temperature, grated",
  "2 slices bread",
  "1 tablespoon butter, room temperature\n"
],
"source_url": "http://www.closetcooking.com/2011/08/buffalo-chicken-grilled-cheese-sandwich.html",
"recipe_id": "35171",
"image_url": "http://static.food2fork.com/Buffalo2BChicken2BGrilled2BCheese2BSandwich2B5002B4983f2702fe4.jpg",
"social_rank": 100,
"publisher_url": "http://closetcooking.com",
"title": "Buffalo Chicken Grilled Cheese Sandwich"}}

您应该在服务器上执行对第三方API的请求。浏览器执行同源策略,防止网站向不共享相同"源"(协议,主机名和端口号的组合)的服务器发出请求。这是一项重要的安全功能,可以防止网站泄露私人信息或恶意行为。

从API获得数据后,需要将其呈现为HTML标记。如果您在服务器上运行Javascript,我会在服务器上呈现它,因为它允许已经禁用JS的用户仍然可以查看呈现的信息。否则,您应该将API数据作为JSON字符串与页面一起发送,以减少服务器往返的次数。

当你使用下划线模板时,你是在用嵌入的Javascript编写标记,它会根据你提供的一些上下文执行。

例如,对于上面的API结果,我们可以制作如下的模板:
var compiledTemplate = _.template(
  '<div>' +
    '<h1><%= title %></h1>' +
    '<p>'
      'Published by ' +
      '<a href="<%= publisher_url %>">' +
        '<%= publisher %>' +
      '</a>' +
    '</p>' +
    '<h2>Ingredients</h2>' +
    '<ul><% _.each(ingredients, function(i) { %>' +
      '<li> <%= i %> </li>' +
    '<% }); %></ul>' +
  '</div>'
)
然后我们可以用上面的数据调用它,只需将数据作为上下文传递给编译后的模板:
var renderedMarkup = compiledTemplate(data);
然后将呈现的标记发送给用户,作为对其请求的响应。

如果您需要更多的帮助来编写下划线模板,请查看官方文档和本指南

最新更新