duankuai6991 2014-02-18 01:42
浏览 47

javascript模板引擎有什么意义? [关闭]

I know the answers people typically give, but I need a concrete example as to why they are needed.

The latest impression I'm getting (mostly from underscore.js) is that it makes the code more PHP like in that you can have <% %> like ?> in PHP

The idea is to make your code less like spaghetti and have a clear difference between presentation and logic. That's what everyone says, but I'm not sure why this warrants the need for a templating engine.

Why can't you just do this in pure javascript? All you need is a function that takes in data as arguments and you can do keep javascript syntax without inventing a new language, which seems ridiculous. For example you can just do:

populateTable(obj) {
    $('#model').html('
    <h2>' + obj.title + '</h2>' +
    <ul> ... </ul>
}

This seems fine to me. It's a function dedicated to rendering a table using some model data that you pass into it. Why do we need to invent new syntax?

  • 写回答

2条回答 默认 最新

  • duanli8391 2014-02-18 01:58
    关注

    One reason for me is that I prefer writing this:

    <div class="entry">
      <h1>{{title}}</h1>
      <div class="body">
        {{body}}
      </div>
    </div>
    

    Over writing this:

    var createEntryTemplate = function(obj) {
      return '<div class="entry">' +
        '<h1>' + obj.title + '</h1>' +
        '<div class="body">' + obj.body +
        '</div>' +
        '</div>';
    };
    

    The latter method is also more error prone - if not for you then maybe for another person. Imagine you're working with a designer who doesn't have a lot of programming experience and he needs to go in and replace a significant chunk of HTML.

    Oh crap...

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行