본문 바로가기
개발

[jquery handlebars] 헬퍼함수 다중조건 if문 사용하기

by 정보알려주는언니 2022. 2. 11.

현재 진행중인 프로젝트에서 jquery handlebars를 사용중이다.

예전회사에서 화면 그리는 용도로 비슷한 플러그인은 사용해봐서 대략적인것들은 사용하는데

전혀 문제가 되지 않았으나, handlebars는 생각보다 제약이 꽤나 많이있었다.

 

그중 가장 불편했던것은 if문의 다중조건이 안된다는점이다.

 

목차

  1. handlebars의 if문 
  2. 위의 if문에서 한단계 진화된 버전
  3. 다중 조건을 사용한 함수

 

 

 

handlebars의 if문 


서론에서도 언급했듯이 handlebars에서는 if문이 다중조건으로 사용이 안된다.

그래서 가이드에 나와있는 내장함수의 if문은 아래와같이 사용 할 수 있다.

 

{{#if author}}
	<h1>{{firstName}} {{lastName}}</h1>
{{/if}}

author가 true일때 h1태그를 노출해주는것이다.

그럼 만약에 거짓일때는? 

 

{{#unless license}}
<h3 class="warning">WARNING: This entry does not have a license!</h3>
{{/unless}}

위와같이 unless로 표현한다. license가 false일때 아래 h3 태그가 노출된다. 

 

https://handlebarsjs.com/

 

Handlebars

 

handlebarsjs.com

 

 

if문에서 한단계 진화된 버전


아니 그러면, 해당 변수가 true이거나 false인 boolean인 경우만 노출이 가능하다는건데

우리는 코딩을 하다보면 수많은 케이스가 있지않은가.

분명 회사에서 뭔가 만들어놨을거같아 찾아보니 cond라는 함수를 만들어놨다.

해당 함수는 아래와같다. 

 

Handlebars.registerHelper('cond', function (v1, operator, v2, options) {
    	switch (operator) {
        	case '==':
        	    return (v1 == v2) ? options.fn(this) : options.inverse(this);
        	case '===':
        	    return (v1 === v2) ? options.fn(this) : options.inverse(this);
        	case '<':
        	    return (v1 < v2) ? options.fn(this) : options.inverse(this);
        	case '<=':
        	    return (v1 <= v2) ? options.fn(this) : options.inverse(this);
       		case '>':
        	    return (v1 > v2) ? options.fn(this) : options.inverse(this);
       		case '>=':
            	return (v1 >= v2) ? options.fn(this) : options.inverse(this);
        	case '&&':
            	return (v1 && v2) ? options.fn(this) : options.inverse(this);
        	case '||':
            	return (v1 || v2) ? options.fn(this) : options.inverse(this);
        	default:
            	return options.inverse(this);
    	}
});

위와같이 신규 함수를 생성해주어, 아래와같이 표현된다.

{{#cond aaa '==' 'test'}}test{{/cond}}

{{#cond aaa '>=' 0}}0보다 크다{{/cond}}

{{#cond aaa '<=' 0}}0보다 작다{{/cond}}

뭔가 굉장히 신박한 표현방법이였다.

뭐 그래도 if와 unless함수보다는 다양한 표현방식이있어서 사용하기 편했다.

 

 

다중 조건을 사용한 함수


위의 cond 함수는 단일 조건을 사용하기엔 편리했으나, 역시 코딩을 하다보면 또 다양한 조건이 있지않은가

조건식에서 조건이 한개만 있는 경우는 거의 없고, 이런 케이스에 대응할 함수도 필요했기 때문에 또 열심히 찾아보았다.

 

 

/**
 * 표현식 그대로 리턴해주는 함수
 * @param expression
 * @param options
 * @returns
 */
Handlebars.registerHelper("x", function(expression, options) {
 var result;

 // you can change the context, or merge it with options.data, options.hash
 var context = this;

 // yup, i use 'with' here to expose the context's properties as block variables
 // you don't need to do {{x 'this.age + 2'}}
 // but you can also do {{x 'age + 2'}}
 // HOWEVER including an UNINITIALIZED var in a expression will return undefined as the result.
 with(context) {
   result = (function() {
     try {
       return eval(expression);
     } catch (e) {
       console.warn('•Expression: {{x \'' + expression + '\'}}\n•JS-Error: ', e, '\n•Context: ', context);
     }
   }).call(context); // to make eval's lexical this=context
 }
 return result;
});



/**
 * 표현식 그대로 if문을 전달받아서 true / false를 return한다.
 * 다중 조건사용을 위해서 만듬
 * @param expression
 * @param options
 * @returns
 */
Handlebars.registerHelper("xif", function (expression, options) {
    return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
});

일단 위와같이 함수를 등록해줘야한다. 

엄청길지만, 우리가 실제 사용할 함수는 xif이므로 xif에 집중하자.

 

 

{{#xif " statusCd == 'A' || typeCd == 'B' "}}on{{/xif}}

위와같이 사용하면 된다.

xif 함수를 호출하게되면 해당함수는 x함수를 호출하게 되는데,

x함수의 경우 내가 보낸 text를 표현식으로 return 해준다. 

 

스택오버플로우에서 구글링했다. 

 

 

https://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional

 

Logical operator in a handlebars.js {{#if}} conditional

Is there a way in handlebars JS to incorporate logical operators into the standard handlebars.js conditional operator? Something like this: {{#if section1 || section2}} .. content {{/if}} I know I

stackoverflow.com

 


댓글