node.js 编写 AngularJs 应用程序时 Jade 或 Handlebars 有什么用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18174856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the use of Jade or Handlebars when writing AngularJs apps
提问by Jay Pete
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.
我是整个 javascript 全栈应用程序的新手(ish),并且是 Angular 的新手,所以我希望有人可以在这里为我直截了当地记录。
Why would I need to use a templating framework like Jade or Handlebars when writing client side apps using AngularJS.
在使用 AngularJS 编写客户端应用程序时,为什么我需要使用像 Jade 或 Handlebars 这样的模板框架。
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.
我应该说我也从未使用过任何这些模板框架。所以我完全不熟悉这些优点。但是,当我查看 Handlebars 时,它会做许多与我在 Angular 中会做的事情相同的事情,例如循环等。
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.
据我所知,最有意义的是使用适当的 HTML 在 Angular 中创建模板,然后在客户端进行所有模板化,并将其与使用 node 和 mongo 的 API 优先方法相结合。
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.
造成这种混乱的原因是我在 GitHub 上找到的很多示例都使用了 Jade,这对我来说似乎违反直觉。
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
谢谢
采纳答案by Engineer
Those who unquestioninglyfavour 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.
那些在 Angular 环境中毫无疑问地喜欢 Jade 的人无法理解视图逻辑属于客户端,而业务逻辑属于服务器,正如 OP 所评论的那样。
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.
除非你有充分的理由,否则不要这样做。在工程中,移动部件较少的系统是更可靠的系统,而尊重接口边界(客户端/服务器)的系统从长远来看更易于维护,因此如果可能,默认为最简单的架构和清晰的分工。如果您有压倒一切的原因,请做您必须做的事情,但要注意 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.
最近我回顾了一些代码,其中直接 Angular 模板会比在 Jade 中混合做得更好,只是通过保持简单性。
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 needtemplate extensibility. Jade is hardly "easier to parse" than HTML. They are but triviallydifferent, while Jade adds another level of indirection - best avoided.
除了模板扩展之外,Jade 还没有带来 Angular 尚未提供的任何有价值的东西。老实说:使用“优先组合而不是继承”(即部分)的合理原则,您不应该需要模板可扩展性。Jade 并不比 HTML“更容易解析”。它们只是微不足道的不同,而 Jade 增加了另一个间接级别 - 最好避免。
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, andyou 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.
服务器端模板有一个有效的特殊情况:优化,记住过早优化通常是一件坏事。如果性能确实存在问题,并且您有足够的服务器容量来处理这个问题,服务器端模板可以提供帮助。这适用于 Twitter 和 Basecamp 等产品,在这些产品中,执行大量服务器端工作的成本被减少对服务器的请求所带来的收益所抵消。
As for Handlebars, there is no need to replace AngularJS's (amazing) client-side templating.
至于 Handlebars,则无需替换 AngularJS 的(惊人的)客户端模板。
回答by thatmarvin
I use Jade to generate templates consumed by AngularJS because I hate writing plain HTML. It looks something like:
我使用 Jade 生成 AngularJS 使用的模板,因为我讨厌编写纯 HTML。它看起来像:
.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='[email protected]'
focus-on='focusEmail'
)
… which I think is a lot cleaner than plain HTML.
... 我认为这比纯 HTML 干净得多。
回答by Chev
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 ;)
除了我发现一个稍微更具人类可读性的方法。略。我不明白为什么人们对这个话题如此狂热。这都是自行车棚。差异可以忽略不计,任何有能力的程序员都可以在谷歌上五秒钟后轻松地将一个翻译成另一个。用你想要的,让其他人无所事事地争吵。选择你的战斗并参与关于真正重要的事情的辩论,比如原子反应堆;)
回答by Dzung Nguyen
- You don't need to use Handlebars with AngularJS since it has it's own template engine.
- 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.
- 你不需要在 AngularJS 中使用 Handlebars,因为它有自己的模板引擎。
- 他们使用 Jade 的原因,因为它只是一个服务器渲染器,它将被编译为 html 并由 angularJS 稍后在前端提供。
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.
所以 TL;DR,在服务器上,你可以使用任何语言 [jade,haml,...] 来为你的应用程序生成 html 结构,它与 angularJS 没有任何关系,因为它会在前端运行时。
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.
您不必在服务器上使用 Jade,我建议不要使用,因为它会使新开发人员感到困惑。在你看到的项目中,他们使用 Jade 只是因为它更干净并且他们习惯了它,如果它与 angularJS 一起使用,它唯一的工作就是生成没有任何逻辑的纯 html。
回答by Mirko
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.
接受的答案有点片面,忽略了这样一个事实,即任何 HTML 预编译器的设置对任何类型的 HTML 项目都有很大的用处:组合和由此产生的标记灵活性。
Working alone on an angular app? Give Jade a try.
独自在 Angular 应用程序上工作?试试翡翠吧。
Jade improves your ability to modularize HTML, decreases the ammount of time you spent on debugging HTML and also encourages building markup inventories.
Jade 提高了模块化 HTML 的能力,减少了调试 HTML 所花费的时间,并鼓励构建标记清单。
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.
在设计期间,HTML 部分可能会有大量的迭代。如果 HTML 输出基于一组 Jade 文件,则团队很容易灵活应对不断变化的需求。此外,通过重新编写 jade 包含来更改标记比重新编写纯 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)
话虽如此,我承认在生产或开发阶段普遍反对将 angular 与 jade 混合。引入另一组必需的语法知识对于大多数团队来说是一个坏主意,并且使用 jade 可能会通过抽象出一些 DRY 原则禁止的工作(例如在标记准备上懒惰)来隐藏低效的项目管理
回答by shabunc
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.
我已经阅读了上面的所有答案,有点惊讶没有人提到使用 jade 而不是生成 AngularJS 模板的一个非常有用的方面。
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 reinitializedangularjs templates.
正如已经说过的,在生产中,输入原始 html 和 jade 之间的现实场景差异实际上是值得注意的,但更重要的是我们永远不要忘记,有时我们需要动态更改和重新初始化angularjs 模板。
To put it simple, sometimeswe 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.
简单来说,有时候我们需要通过innerHTML来改变html,然后强制AngularJS重新编译内容。这正是通过 jade 生成此类视图可以带来好处的任务类型。
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.
此外,AngularJS 可以很好地处理模型,根据定义,模型的结构是众所周知的。实际上,我们实际上并不知道确切的结构(想象一下,比如说,JSON 渲染器)。AngularJS 在这里会很笨拙(即使他们正在构建一个 Angular 应用程序),而 jade 会完成这项工作。
回答by suryasankar
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.
Jade 肯定比 Haml 更接近 html。所以上下文切换实际上非常小。然而,它也并非完全没有。这对开发人员来说可能根本无关紧要。但是,当您的设计师来询问您如何使嵌套标签正常工作时,您正在解决您首先创建的一个不必要的问题。
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.
HTML 仍然可以写得非常清晰,并且可以使用部分来使其更易于理解。500 行任何内容都难以阅读——无论是 Jade 还是 HTML。
Here is a Jade template
这是一个 Jade 模板
.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
和等效的 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 )
当书写清晰时,我不认为 HTML 是非常不利的,以保证转换。果然,尖括号很碍眼。但是我宁愿拥有它们,也不必处理设计者的疑问,我引入的间接性是否破坏了 html。(可能不会。但证明它不是值得的努力)
回答by Austin Pray
You can include angular templates via Jade.
您可以通过 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.
对于缓存模板,我认为这比在 javascript 文件中包含转义模板要脆弱得多。
See: https://docs.angularjs.org/api/ng/service/$templateCache
请参阅:https: //docs.angularjs.org/api/ng/service/$templateCache
回答by Arjan
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.
在团队中工作时,前端可能更喜欢将他们的页面设计为静态 html。将静态 html 翻译成动态模板是错误的来源,而添加 jade 会增加这样的翻译步骤。
As many others, I favour simplicity!
和其他许多人一样,我喜欢简单!
回答by alex
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.
好吧,模板在这种情况下很方便,尽管人们有时会使用像 Jekyll 这样的静态 html 生成器。
There is another reason for using Jade that's not mentioned here before.
使用 Jade 的另一个原因是这里没有提到的。
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.
如果您正在编写带有缩进和换行符的可人工维护的 HTML,则每个换行符都会产生一个空白文本节点。在某些情况下,它几乎可以破坏内联元素的格式,并使 javascript 代码更加奇怪。
You can read more details here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM
您可以在此处阅读更多详细信息: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.
如果您正在编写 Jade 代码,它会被编译成没有此问题的单行 HTML。

