동적 템플릿 리터럴
추천0
페이지 정보
작성자 GrapeCity 작성일 2019-11-17 15:54 조회 5,240회 댓글 0건본문
관련링크
Wijmo 2019 v3 릴리스에서는 cellTemplate 속성을 FlexGrid 열에 추가했습니다. 이 속성을 통해 개발자는 템플릿 리터럴 표현식을 사용하여 셀의 컨텐츠를 생성할 수 있습니다.
템플릿 리터럴 표현식을 사용하는 것의 장점은 계산을 지원하므로 실제 JavaScript 코드를 작성하지 않고도 셀에 조건부 서식을 적용할 수 있다는 것입니다. 예를 들면 다음과 같습니다.
// simple/default rendering with template string col.cellTemplate = '${value}:${col.format}'; // conditional formatting with template string col.cellTemplate = '<span class=${value > 40000 ? "big-val" : "small-val"}>${text}</span>';
템플릿 리터럴을 사용하고 있지만 속성은 표준 문자열로 지정됩니다 (백틱(`) 없음). 이것은 속성을 할당할 때 템플릿을 평가하지 않기 때문에 필요합니다. 셀이 렌더링 될 때 나중에 평가하고자 합니다.
이를 위해, Wijmo에 evalTemplate 함수를 추가했습니다. 이 함수는 리터럴 템플릿 표현식이 포함된 템플릿 문자열과 표현식을 평가하기 위한 변수를 제공하는 컨텍스트 객체를 사용합니다.
우리는 이것이 일반적인 시나리오라고 생각하므로 이 함수는 public이며 앱에서 사용할 수 있습니다.
evalTemplate 함수는 두 개의 추가 기능을 제공합니다 :
- 내장 세계화/서식 기능이 있는 경우 Wijmo의 glbz 태그 기능 제공
- 템플릿 리터럴을 지원하지 않는 레거시 브라우저(IE)에서 작동합니다.
Wijmo의 evalTemplate 함수의 소스 코드는 다음과 같습니다.
export function evalTemplate(template: string, ctx?: any): string { if (isIE()) { // // in IE, use a regex to extract the template items and format strings // from the template string: let rx = /\${([^}]*)}(:(([A-Za-z]\d*)|"([^"]+)"|'([^']+)'))?/g; return template.replace(rx, (t, expr, f, fmt, fRaw, fQ2, fQ1) => { // // calculate the resule let result = _evalExpression(expr, ctx); // // format the result (plays the role of glbz) return fmt ? Globalize.format(result, fRaw || fQ2 || fQ1) : result; }); } else { // // not IE, let JavaScript and glbz evaluate the template string return _evalExpression(template, ctx) } } function _evalExpression(expr: string, ctx: any): string { // // make sure we have a template, include the glbz tag function ctx = ctx || {}; ctx.glbz = glbz; // // get keys and values from context object let keys = Object.keys(ctx); let vals = keys.map(e => ctx[e]); // // build a function to evaluate the template literal let fn = isIE() ? new Function(...keys, 'return ' + expr) : new Function(...keys, 'return glbz`' + expr + '`'); // // call the function and return the result return fn(...vals); }
IE는 더 이상 인기있는 브라우저는 아니지만, 국내 사용자의 약 20%가 여전히 이 브라우저에 의존하고 있기 때문에, IE에서 동적 템플릿 리터럴을 지원한다는 것이 큰 장점으로 작용할 것이라고 생각합니다.
댓글목록
등록된 댓글이 없습니다.