Java Script

Handlebars

Jassy 2020. 8. 4. 16:27

 

핸들 바의 경우 JavaScript를 사용하여 재사용 가능한 HTML을 생성 할 수있는 템플릿 엔진이 제공됩니다. 

또 다른 이점은 핸들 바는 HTML이나 JavaScript를 작성할 때 명확하게 분리된다는 것입니다.


The major steps of using Handlebars in a project:

Add the Handlebars library to your project. — one option is to use a Content Delivery Network (CDN): MDN CDN documentation.
Create a Handlebars script in your HTML file.
In your JavaScript file, grab the HTML stored in the Handlebars script.
Use Handlebars.compile() to return a templating function.
Pass in a context object to the templating function to get a compiled template.
Render the compiled template onto the web page.


핸들 바의 힘은 재사용 성과 확장성에 있습니다. 

핸들 바 표현을 통해 이를 달성 할 수 있습니다.

스크립트 내에서 핸들 바 표현식은 이중 괄호로 묶습니다 {{ }}. 

중괄호 안의 내용은 자리 표시 자 역할을합니다.

 

<!DOCTYPE html>
<html>
  <head>
  
    <script id="greet" type="text/x-handlebars-template">{{greeting}}</script>
    
    <meta charset="utf-8">
    <title>Hello World!</title>
    <link type="text/css" rel="stylesheet" href="public/style.css">
    <script src="handlebars.min.js"></script>
    
  </head>
  <body>
    <div class="container">
      <h1>Handlebar Expressions</h1>
      <div id="hello">
      </div>
      <div class="blinker">|</div>
    </div>  
    <script src="public/main.js" type="text/javascript"></script>
  </body>
</html>
const source = document.getElementById('greet').innerHTML;

const template = Handlebars.compile(source);

const context = {greeting : 'Hello World!'}

const compiledHtml = template(context);

const fill = document.getElementById('hello');
fill.innerHTML = compiledHtml ;

{{if}}

지금까지는 핸들 바 표현식 만 사용하여 템플릿에 값을 삽입했습니다. 

값을 삽입하기 전에 특정 객체 속성을 확인하려는 경우 핸들 바는 {{if}}도우미 블록을 제공합니다 . 

{{if}}도우미는 비슷합니다 if자바 스크립트의 조건, 그러나 구문에 차이가 있습니다 :

 

{{#if argument}}
  // Code to include if the provided argument is truthy 
{{/if}}

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>GIF!</title>
    <script src="handlebars.min.js"></script>
		<link rel="stylesheet" type="text/css" href="public/style.css">
	  <script id="ifHelper" type="text/x-handlebars-template">
      
    {{#if opinion}}
      <p>"The correct way to say 'GIF' is GIF!"</p>
    {{/if}}
 
    </script>    
  </head>
  <body>
    <div class="bg">
      <img class="bg-convo" src="https://s3.amazonaws.com/codecademy-content/courses/learn-handlebars/handlebars+if.svg">
    </div>
    <div id="debate">
    </div>
  </body>
  <script src="public/main.js" type="text/javascript"></script>
</html>
const source = document.getElementById('ifHelper').innerHTML;
const template = Handlebars.compile(source);

const context = {
  opinion : true
}
const compiledHtml = template(context);

const debateElement = document.getElementById('debate');
debateElement.innerHTML = compiledHtml;

{{else}}

 

이전 연습에서는 {{if}}컴파일 된 HTML에 코드 블록이 포함되어야하는지 여부를 결정하는 데 사용 했습니다. 

그러나 그 주장이 거짓으로 판명되면 HTML에 빈 섹션이 있습니다!

대신 Handlebar의 {{else}} 표현식을 사용하여 else 섹션 을 만들어 기본 코드 줄을 추가 할 수 있습니다 .

 

{{#if argument}}
  // Code to include if the provided argument is truthy 
{{else}}
  // Code to include if the provided argument is falsy 
{{/if}}

{{each}}

 

 

Handlebars가 제공하는 또 다른 도우미 {{each}}는 배열을 반복 할 수 있는 블록입니다. 

{{if}}블록 과 마찬가지로 여는 {{#each}}식과 닫는 {{/each}}식이 있습니다. 

내측 {{each}}블록 {{this}}반복의 요소에 대한 자리로서 작용한다.

 

{{#each someArray}}
  <p>{{this}} is the current element!</p>
{{/each}}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Each Block[s]</title>
    <link href="public/style.css" type="text/css" rel="stylesheet">
    <script src="handlebars.min.js"></script>

    <script id="eachHelper" type="text/x-handlebars-template">

    {{#each newArray}}
      <div class="block">{{this}}</div>
    {{/each}}
    
    </script>
  </head>
  <body>
    <h1>Each Block[s]</h1>
    <div id="display">
    </div>
    <script src="public/main.js" type="text/javascript"></script>
  </body>
</html>
const source = document.getElementById('eachHelper').innerHTML;
const template = Handlebars.compile(source);

const context = {
  newArray: [1,2,3,4,5,6,7,8,9,10]
};

const compiledHtml = template(context);

const displayElements = document.getElementById('display');
displayElements.innerHTML = compiledHtml;

{{this}}

 

{{this}}를 사용하면 반복되는 요소의 속성에 액세스 할 수 있습니다.

{{#each someArray}}
  <p>The current shape is: {{this.shape}}!</p>
{{/each}}
const context = {
  someArray: [
    {shape: 'Triangle'},
    {shape: 'Circle'},
    {shape: 'Square'}
  ] 
}

/*
<p>The current shape is: Triangle!</p>
<p>The current shape is: Circle!</p>
<p>The current shape is: Square!</p>
*/

Combining "If" and "Each"