项目帮助:下划线模板

Project help: underscore template

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

该应用程序假设从 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"}}

您应该在服务器上向第 3 方 API 执行请求。浏览器强制执行 Same-origin policy,这会阻止网站向不共享相同 "origin"(协议、主机名和端口号的组合)的服务器发出请求。这是一项基本的安全功能,可防止网站泄露私人信息或恶意行为。

从 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);

然后您可以将呈现的标记作为对他们请求的响应发送给用户。

如果您在编写下划线模板时需要更多帮助,请查看 official docs and this guide