Code Metaphor

Programming, Writing, Reading, Thoughts…

Template.js: String Interpolation in JavaScript with MooTools

Prototype에도 Ruby 문자열의 내삽법(interpolation)을 조악하게 따라한 Template 클래스가 있길래, 내가 MooTools로 제대로 구현해봤다.

사용법은 간단하다.

"string interpolation".interpolate(context, options)

위와 같이 사용하면 된다. options 인자는 없어도 그만인데, 없을 경우 내삽할(to interpolate) 표현식을 감싸는 문자열은 #()가 된다. 아래는 간단한 예시.

'<code>${name}</code> class by <a href="${author.url.trim()}">${author.name}</a>'.interpolate({
    name: 'Template',
    author: {
        name: 'Hong, MinHee',
        url: 'http://dahlia.pe.kr/'
    }
}, {
    begin: '${',
    end: '}'
})

보다시피 메서드나 함수를 평가하는 등의 복잡한 모든 종류의 표현식을 사용할 수 있는 것이 Prototype 버전의 Template과 다른 점이다(Prototype 내장 Template은 JavaScript 표현식 코드를 평가하는 것이 아니라, 오직 식별자만을 단순 치환하는 형식이다).

저 코드는 아래의 문자열을 반환한다.

<code>Template</code> class by <a href="http://dahlia.pe.kr/">Hong, MinHee</a>

MIT 스타일 라이센스이고, 소스는 아래에서 받을 수 있다.

덧. 좀더 극적인 예제: "#(file): #((function() { return 'String Interpolation in #(language) with #(framework)' })().interpolate({language: 'JavaScript', framework: 'MooTools'}))".interpolate({file: 'Template.js'})

This entry was posted on August 10, 2007 at 6:22 PM. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

3 Responses to “Template.js: String Interpolation in JavaScript with MooTools”

  1. 거친마루 Says:

    반복영역이 지원되는 템플릿 버전은 없나요? : )

  2. Hong, MinHee (DAHLIA) Says:

    반복영역이 지원되는 템플릿 버전은 없나요? : )

    혹시 반복문을 말씀하시는 건가요? 일단 표현식(expression) 코드만 지원하고 있어요. 표현식이 아닌 코드는 무얼 반환해야 하는지도 모르겠고 해서요.

  3. 이흥섭 Says:

    "#(file): #((function() { return 'String Interpolation in #(language) with #(framework)' })().interpolate({language: 'JavaScript', framework: 'MooTools'}))".interpolate({file: 'Template.js'})

    아름답습니다.

Powered by WordPress. Styled by Hong, MinHee. XML Feed, Comments XML Feed.