AngularJs 앱을 작성할 때 Jade 또는 Handlebars를 사용하는 것은 무엇입니까
나는 전체 자바 스크립트 풀 스택 응용 프로그램에 익숙하지 않으며 Angular에 완전히 익숙하지 않기 때문에 누군가 나를 위해 레코드를 바로 넣을 수 있기를 바랍니다.
AngularJS를 사용하여 클라이언트 측 앱을 작성할 때 Jade 또는 Handlebars와 같은 템플릿 프레임 워크를 사용해야하는 이유는 무엇입니까?
나는 이러한 템플릿 프레임 워크를 사용한 적이 없다고 말해야한다. 그래서 나는 이점에 완전히 익숙하지 않습니다. 그러나 예를 들어 Handlebars를 살펴보면 루핑 등과 같이 Angular에서와 같은 많은 작업을 수행합니다.
내가 알 수있는 한 적절한 HTML을 사용하여 Angular로 템플릿을 만든 다음 모든 템플릿 클라이언트 측을 수행하고 예를 들어 node 및 mongo를 사용하여 API 우선 접근 방식과 결합하는 것이 가장 합리적입니다.
이 혼란의 이유는 GitHub에서 찾은 많은 예제가 Jade를 사용하기 때문에 직관적이지 않은 것 같습니다.
나를 깨우 치고 똑바로 세우십시오. 저보다 훨씬 더 많은 사람들로부터 모범 사례를 배우고 싶습니다.
감사
의심 할 여지없이 Angular 환경에서 Jade를 선호 하는 사람들 은 OP가 언급 한 것처럼 뷰 로직이 클라이언트에 있고 서버에 비즈니스 로직이 있다는 것을 이해하지 못합니다.
그럴만한 이유가 없다면 그렇게하지 마십시오. 엔지니어링에서 움직이는 부품 수가 적은 시스템은보다 안정적인 시스템이며, 인터페이스 경계 (클라이언트 / 서버)가 존중되는 시스템은 장기적으로 유지 관리가 가능하므로 가능한 경우 가장 간단한 아키텍처와 깔끔한 노동 분담이 기본입니다. 우선적 인 이유가 있다면 반드시해야 할 일을하되 주의를 기울이십시오 .
최근에 간단한 Angular templating이 단순성을 유지함으로써 Jade에서 혼합하는 것보다 훨씬 나은 작업을 수행 한 코드를 검토했습니다.
템플릿 확장 외에도 Jade는 Angular가 아직 제공하지 않은 테이블에 가치가 없습니다. 솔직하게 말하자 : "상속보다 선호하는 구성"(즉, 부분)에 대한 올바른 원칙을 사용하면 템플릿 확장 성 이 필요 하지 않습니다 . Jade는 HTML보다 "파싱하기가 쉽지 않습니다". 그들은하지만 있습니다 하찮게 피해야 - 옥 간접의 또 다른 레벨을 추가하면서, 다른.
서버 측 템플릿에 대한 하나의 유효한 특수 사례가 있습니다. 최적화 : 조기 최적화는 일반적으로 나쁜 것임을 기억합니다. 성능이 실제로 문제가 되고 이를 처리하기 위해 여분의 서버 용량이있는 경우 서버 측 템플릿이 도움을 줄 수 있습니다. 이는 많은 서버 측 작업을 수행하는 비용이 서버에 대한 요청 감소로 인해 상쇄되는 Twitter 및 Basecamp와 같은 제품에 적용됩니다.
핸들 바는 AngularJS (놀라운) 클라이언트 측 템플릿을 대체 할 필요가 없습니다.
일반 HTML을 작성하는 것을 싫어하기 때문에 Jade를 사용하여 AngularJS가 사용하는 템플릿을 생성합니다. 다음과 같이 보입니다.
.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'
)
… 평범한 HTML보다 훨씬 깨끗하다고 생각합니다.
나는 사람들이 왜 이것의 차이점에 관심이 있는지 이해하지 못한다.
<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>
이:
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 ;)
- 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.
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.
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)
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.
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
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 )
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.
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!
'Programing' 카테고리의 다른 글
인터페이스를 구현하는 추상 클래스가 왜 인터페이스 메소드 중 하나의 선언 / 구현을 놓칠 수 있습니까? (0) | 2020.07.14 |
---|---|
R에서 키 누르기를 기다리는 방법? (0) | 2020.07.14 |
파이썬에서 문자열로 유니 코드를 선언하는 이유는 무엇입니까? (0) | 2020.07.14 |
ImportError : numpy.core.multiarray를 가져 오지 못했습니다. (0) | 2020.07.14 |
약속에 onFulfilled에 여러 가지 주장이있을 수 있습니까? (0) | 2020.07.14 |