What's the use of Jade or Handlebars when writ

2019-01-16 01:36发布

问题:

I am new(ish) to the whole javascript full stack applications, and completely new to Angular, so I was hoping somebody can put the record straight for me here.

Why would I need to use a templating framework like Jade or Handlebars when writing client side apps using AngularJS.

I should say that I have never used any of these templating frameworks either. So I am not familiar with the advantages completely. But when I look at Handlebars for example, it does many of the same things as I would do in Angular, such as looping etc.

As far as I can tell, it would make most sense to create the templates in Angular using proper HTML and then do all templating client side, and combine this with an API first approach using node and mongo for example.

The reason for this confusion is that a lot of the examples I find on GitHub make use of Jade, and it seems counter intuitive for me.

Please enlighten me, and set me straight. I would love to learn some best practices from people who know much more than I do.

Thanks

回答1:

Those who unquestioningly favour Jade in an Angular environment fail to understand that view logic belongs on the client, and business logic on the server, just as the OP commented.

Don't do it unless you have a very good reason to do it. In engineering, a system with fewer moving parts is a more reliable system, and a system where interface boundaries (client/server) are respected is more maintainable over the long term, so default to the simplest architecture and clean division of labour if possible. If you have overriding reasons, do what you must, but caveat emptor.

Recently I reviewed some code where straight Angular templating would have done a far better job than mixing in Jade, just through maintaining simplicity.

Aside from template extension, Jade brings nothing worthwhile to the table that Angular doesn't already supply. Let's be honest: Using the sound principle of "favour composition over inheritance" (i.e. partials), you shouldn't ever need template extensibility. Jade is hardly "easier to parse" than HTML. They are but trivially different, while Jade adds another level of indirection - best avoided.

There is one valid, specialised case for server-side templating: Optimisation, remembering that premature optimisation is generally a Bad Thing. Where performance is truly at issue, and you have the server capacity to spare to handle this, server side templating can assist. This applies to products like Twitter and Basecamp, where the cost of doing a lot of server side work is offset by the gains of reduced requests to the server.

As for Handlebars, there is no need to replace AngularJS's (amazing) client-side templating.



回答2:

I use Jade to generate templates consumed by AngularJS because I hate writing plain HTML. It looks something like:

.control-group(
  ng-form
  name='emailGroup'
  ng-class='{"ng-error": emailGroup.$invalid}'
)
  label.control-label Email
  .controls
    input(
      type='email'
      ng-model='user.email'
      required
      placeholder='you@example.com'
      focus-on='focusEmail'
    )

… which I think is a lot cleaner than plain HTML.



回答3:

I honestly don't understand why people care about the difference between this:

<html ng-app>
 <!-- Body tag augmented with ngController directive  -->
 <body ng-controller="MyController">
   <input ng-model="foo" value="bar">
   <!-- Button tag with ng-click directive, and string expression 'buttonText' wrapped in "{{ }}" markup -->
   <button ng-click="changeFoo()">{{buttonText}}</button>
   <script src="angular.js">
 </body>
</html>

and this:

html(ng-app="ng-app")
  // Body tag augmented with ngController directive  
  body(ng-controller="MyController")
    input(ng-model="foo", value="bar")
    // Button tag with ng-click directive, and string expression 'buttonText' wrapped in "{{ }}" markup
    button(ng-click="changeFoo()") {{buttonText}}
    script(src="angular.js")

Except that I find one slightly more human-readable. Slightly. I don't get why people are so fervent about the topic. It's all bikeshedding. The difference is negligible and any competent programmer could easily translate one into the other after five seconds on Google. Use what you want and let everyone else quarrel over nothing. Pick your battles and engage in debates about things that actually matter, like atomic reactors ;)



回答4:

  1. You don't need to use Handlebars with AngularJS since it has it's own template engine.
  2. The reason they use Jade, because it's just a server renderer which will be compiled to html and served by angularJS later on the frontend.

So TL;DR, on server, you can use whatever language [jade,haml,...] to generate just html structure for your application, it doesn't have anything to do with angularJS since it will render and work with HTML at runtime on frontend.

You don't have to use Jade on server, and I suggest not using since it will confuse new developers. In projects that you see they use Jade only because it's cleaner and they are used to it, and if it uses with angularJS, it's only job is to generate plain html without any logic.



回答5:

The accepted answer is somewhat one-sided and neglects the fact that any setup of pre-compiler for HTML has a great use for ANY kind of HTML project: Composition and resulting markup flexibility.

Working alone on an angular app? Give Jade a try.

Jade improves your ability to modularize HTML, decreases the ammount of time you spent on debugging HTML and also encourages building markup inventories.

During design time there can be an awful amount of iteration on HTML parts. If HTML output is based on a set of jade files, it's easy for the team to act flexible on changing requirements. Also, changing the markup via re-composing jade includes is significantly more robust than re-writing pure HTML.

That being said, i recognize the general aversion towards mixing angular with jade in production or development stage. Introducing another required set of syntax knowledge is a bad idea for most teams and the use of jade might hide inefficient project management by abstracting away some work that would be prohibited by DRY principles (e.g. being lazy on markup preparation)



回答6:

I've read all the answers above and was a bit surprised no one had mentioned one aspect which makes using jade over generating AngularJS templates a very useful thing.

As it already been told, in production, realistic scenarios difference between typing raw html and jade is actually notable, but the more important thing we should never forget is that sometimes we need dynamically changed and reinitialized angularjs templates.

To put it simple, sometimes we need to change html via innerHTML and then force AngularJS to recompile contents. And this is exactly the type of task when generating such views via jade can have it benefits.

Also, AngularJS works well with models, which structure is by definition well known. Actually, it happens that we actually don't know the exact structure (imagine, say, JSON renderer). AngularJS will be quite clumsy here (even if were are building an angular app), while jade will do the job.



回答7:

You can include angular templates via Jade.

script(type="text/ng-template", id="admin")
  include partials/admin

For caching templates I perceive this as much less fragile than including the escaped templates in the javascript files.

See: https://docs.angularjs.org/api/ng/service/$templateCache



回答8:

Jade is definitely much more closer to html than say Haml. So the context switch is actually very minimal. Yet it is not completely absent. It may not matter to a developer at all. But when your designer comes and asks you how to get a nested tag to work properly, you are solving an unnecessary problem that you created in the first place.

HTML can still be written very legibly and partials can be used to make it more comprehensible. 500 lines of anything is hard to read - be it Jade or HTML.

Here is a Jade template

.product-container

    .input-group.msB.col-md-5.no-padding
        .fnt-light-navyblue.mtB(for='name')
            strong Name the sticker
        input.full-input(type='text', placeholder='Awesome Batman Sticker')
    .clear

    .form-group.mmT
        label.form-label.fnt-light-navyblue
            strong Choose size
        .selector-group(ng-repeat="size in sizes", ng-class="{ 'msT': !$first}")
            - raw
            span.radio
                input.radio(name='choose_sticker_size',
                            ng-model="selectedSize",
                            type='radio',
                            value='{{size}}',
                            id="sticker-{{size}}")
                span.fake-radio
            label(for='sticker-{{size}}') {{size}} inch
            - endraw
    // end form-group
    .clear

And the equivalent HTML

<div class="product-container">

    <div class="input-group msB col-md-5 no-padding">
        <div for="name" class="fnt-light-navyblue mtB">
            <strong>Name the product</strong>
        </div>
        <input type="text" placeholder="Awesome Batman Sticker" class="full-input" />
    </div>
    <div class="clear"></div>

    <div class="form-group mmT">
        <label class="form-label fnt-light-navyblue">
            <strong>Choose size</strong>
        </label>
        <div
            class="selector-group"
            ng-class="{ 'msT': !$first}"
            ng-repeat="size in sizes">
                {% raw %}
                <span class="radio">
                    <input
                        id="sticker-{{size}}"
                        class="radio"
                        name="choose_sticker_size"
                        ng-model="selectedSize"
                        type="radio"
                        value="{{ size }}" />
                    <span class="fake-radio"></span>
                </span>
                <label for="sticker-{{size}}">{{size}}</label>
                {% endraw %}
        </div>
    </div><!-- end form-group -->
    <div class="clear"></div>
</div>

When written legibly I dont see HTML to be very particularly disadvantaged so as to warrant a switch. Sure enough, the angular brackets are an eyesore. But I would rather have them, than having to deal with the designer's doubts whether the indirection I introduced is breaking the html. ( It may not. But proving it is not a worthy effort )



回答9:

First of all, you always need some kind of server-side templating.

Pure client-side templating have huge disadvantages in a loading time, so it's often mitigated by rendering some static elements on the server. This way when user partially loads a page, he'll already see some elements on the page.

And well, templates are handy in this case, although people sometimes use static html generator like Jekyll instead.


There is another reason for using Jade that's not mentioned here before.

Whitespace.

If you're writing human-maintainable HTML with indentations and line-breaks, every single linebreak will result in a whitespace text node. It can pretty much screw formatting of inline elements in some cases, and make javascript code more weird.

You can read more details here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM

If you're writing Jade code, it is compiled into one-line HTML that doesn't have this issue.



回答10:

When working in a team, front-end likely prefers designing their pages as static html. Translating that static html into dynamic templates is a source of errors, and adding jade adds such translation step.

As many others, I favour simplicity!