Program Tip

Handlebars.js와 함께 사전 컴파일 된 템플릿 사용 (jQuery Mobile 환경)

programtip 2020. 11. 10. 22:10
반응형

Handlebars.js와 함께 사전 컴파일 된 템플릿 사용 (jQuery Mobile 환경)


Handlebars에서 템플릿을 미리 컴파일하는 데 다소 어려움을 겪고 있습니다. 내 jQuery Mobile 프로젝트가 템플릿 측면에서 상당히 커지고 있으며 내가 사용하는 템플릿을 미리 컴파일하고 싶습니다.

그러나 핸들 바로이를 수행하는 방법에 대한 좋은 설명 (단계별 자습서와 같은)을 찾을 수없는 것 같습니다.

여전히 스크립트 태그를 사용하여 템플릿을 모두 인라인으로 유지합니다. NPM을 사용하여 핸들 바를 설치했습니다. 하지만 지금은 어떻게 진행해야할지 모르겠습니다.

나는 뭔가를 할 것 같아요

handlebars -s event.handlebars > event.compiled

그리고 어떻게 든 event.compiled 내용을 포함합니까? 하지만 어떻게 부르는지.

내 템플릿을 이렇게 부르고 있습니다.

var source = $('#tmpl_profile').html(),
template = Handlebars.compile(source),
context = user.profile()),
html    = template(context);

누군가 나를 위해 이것에 대해 밝힐 수 있기를 바랍니다.


그래서 많은 시행 착오 끝에 (이것이 그것을 배우는 가장 좋은 방법입니다) 여기 저에게 맞는 방법이 있습니다.

먼저 모든 템플릿을 외부화합니다. 예를 들어 스크립트 태그 안에 템플릿이 있다고 가정합니다.

<script id="tmpl_ownevents" type="text/templates">
    {{#unless event}}
        <div class="notfoundevents"><p>No events for you</p></div>    
    {{/unless}}
</script>

events.tmpl이라는 새 파일을 만들고 여기에 템플릿을 복사 / 붙여 넣기합니다. 스크립트 요소 자체를 제거해야합니다.이 문제는 a ..

다음과 같이 Handlebars 명령 줄 스크립트를 설치합니다.

npm install -g handlebars

events.tmpl을 저장 한 폴더로 이동하여 실행하십시오.

handlebars events.tmpl -f events.tmpl.js

Handlebars.js를 포함시킨 후 컴파일 된 자바 스크립트를 HTML에 포함합니다.

<script src="events.tmpl.js"></script>

이제 남은 것은 일반 템플릿 코드를 다음과 유사한 것으로 변경하는 것입니다.

var template = Handlebars.templates['events.tmpl'], // your template minus the .js
    context = events.all(), // your data
    html    = template(context);

그리고 거기에 초고속 사전 컴파일 된 Handlebars 템플릿이 있습니다.


이를위한 또 다른 좋은 옵션은 GruntJS 를 사용하는 입니다. 설치 후 :

npm install grunt-contrib-handlebars --save-dev

그런 다음 gruntfile.js 내부

grunt.initConfig({
    dirs: {
      handlebars: 'app/handlebars'
    },
    watch: {
      handlebars: {
        files: ['<%= handlebars.compile.src %>'],
        tasks: ['handlebars:compile']
      }
    },
    handlebars: {
      compile: {
        src: '<%= dirs.handlebars %>/*.handlebars',
        dest: '<%= dirs.handlebars %>/handlebars-templates.js'
      }
    }
});


grunt.loadNpmTasks('grunt-contrib-handlebars');

그런 다음 grunt watch콘솔에서 입력 하기 만하면 grunt가 모든 * .handlebars 파일을 handlebars-templates.js 파일로 자동 컴파일합니다.

핸들 바로 작업하는 정말 멋진 방법입니다.


내가하는 방법은 다음과 같습니다.

예비

모든 템플릿 변수가 다음과 같은 변수에 있다고 가정합니다 context.

var context = {
    name: "Test Person",
    ...
};

템플릿을 넣을 위치

모든 템플릿을 포함하는 디렉토리를 생성합니다 . templates/여기에라는 템플릿을 추가합니다 filename.handlebars.

디렉토리 구조 :

.
└── templates
    ├── another_template.handlebars
    └── my_template.handelbars

템플릿 컴파일

먼저 루트 디렉토리로 이동 한 다음 npm CLI 프로그램으로 템플릿을 컴파일합니다.

handlebars templates/*.handlebars -f compiled.js

새 디렉토리 구조 :

.
├── compiled.js
└── templates
    ├── another_template.handlebars
    └── my_template.handlebars

용법

포함] compiled.js당신은 런타임을 포함 한 후 HTML 페이지를 :

<script src="handlebars.runtime.js"></script>
<script src="compiled.js"></script>

전역 Handlebars개체를 사용하여 템플릿을 렌더링합니다 .

// If you used JavaScript object property conform file names
// Original filename: "my_template.handlebars"
Handlebars.templates.my_template(context)

// if you used special characters which are not allowed in JavaScript properties
// Original filename: "my-template.handlebars"
Handlebars.templates["my-template"](context)

비고

파일 확장자 .handlebars. 템플릿을 컴파일 할 때 자동으로 제거됩니다.

추가 : Handlebars / Mustache 플러그인 과 함께 Jetbrains IDE 중 하나를 사용 하면 상당히 좋은 편집기 지원을받을 수도 있습니다.


Grunt로 핸들 바 템플릿 미리 컴파일하기

Node.js가 설치되어 있다고 가정합니다. 그렇지 않다면 가서하십시오.

1) 노드 종속성 설정 :

응용 프로그램 루트 디렉터리에 package.json. 해당 파일에 다음을 붙여 넣으십시오.

{
  "devDependencies": {
   "grunt-contrib-handlebars": "~0.6.0",
    "grunt-contrib-watch": "~0.5.3",
    "handlebars": "~1.3.0"
  },
}

이 JSON 파일은 Node에 어떤 패키지를 설치해야하는지 알려줍니다. 이렇게하면 다음 단계에서 볼 수 있듯이 다른 개발자가 매우 빠르게 시작하고 실행할 수 있습니다.

2) 노드 종속성 설치 :

터미널 / 명령 프롬프트 / powershell에서 cd프로젝트 루트 디렉터리로 이동하고 다음 명령을 실행합니다.

npm install grunt -g
npm install grunt-cli -g

And to install the dependencies listed in your package.json:

npm install

Now you've installed all of the node dependencies that you need. In your projects root directory, you'll see a node_modules folder.

3) Configuring Grunt:

In your projects root directory, create a file named Gruntfile.js. Paste the following into that file:

module.exports = function(grunt) {

    var TEMPLATES_LOCATION        = "./src/templates/",       // don't forget the trailing /
        TEMPLATES_EXTENSION       = ".hbs",
        TEMPLATES_OUTPUT_LOCATION = TEMPLATES_LOCATION,       // don't forget the trailing /
        TEMPLATES_OUTPUT_FILENAME = "compiled_templates.js";  // don't forget the .js

    grunt.initConfig({
        watch: {
            handlebars: {
                files: [TEMPLATES_LOCATION + '**/*' + TEMPLATES_EXTENSION],
                tasks: ['handlebars:compile']
            }
        },
        handlebars: {
            compile: {
                src: TEMPLATES_LOCATION + '**/*' + TEMPLATES_EXTENSION,
                dest: TEMPLATES_OUTPUT_LOCATION + TEMPLATES_OUTPUT_FILENAME,
                options: {
                    amd: true,
                    namespace: "templates"
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-handlebars');
    grunt.loadNpmTasks('grunt-contrib-watch');

}

4) Configuring to Your Liking:

If you are not using Require.js, you'll want to change handlebars.compile.options.amd to false. You may also want to tweak the namespace option to your liking. If you're using require/amd modules, the namespace property is unimportant (it's default is "JST", if you remove it).

Because all project structures are a little bit different, you'll need to configure the Gruntfile just a little bit. Modify the constants TEMPLATES_LOCATION, TEMPLATES_EXTENSION, TEMPLATES_OUTPUT_LOCATION, TEMPLATES_OUTPUT_FILENAME to fit your project.

If your templates are scattered throughout your application, you'll want to change TEMPLATES_LOCATION to the lowest directory possible. Make sure your templates are isolated from your node_modules, bower_components or any other 3rd party directories, because you don't want Grunt to compile 3rd Party templates into your applications compiled templates. If you include all of your own code in a ./src, ./js, ./app directory, you'll be okay.

5) Compiling templates with Grunt:

To run grunt in the background, open your terminal and cd into your projects root directory and run the command: grunt watch:handlebars (just grunt watch works as well). With grunt running in the background, all changes to your template files will be automatically compiled and the output file specified handlebars.compile.dest will be rewritten as needed. The output will look something like this:

Running "watch" task
Waiting...

To run the compile task alone, open your terminal and cd into your projects root directory and run the command: grunt handlebars:compile (just grunt:handlebars works as well). The output will look something like:

Running "handlebars:compile" <handlebars> task
File "./src/templates/compiled_templates.js" created.

Done, without errors.

For Handlebars 2.0.0 alpha Update:

@Macro has explained quite clearly how it works with 1 piece of template, please see this answer for how to make handlebars.js works

If you see "TypeError: 'undefined' is not a function" when using precompiled templates:

This error happened at "handlebar.runtime.js" line 436 when evaluting templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data),

because the compiler npm installed is not matching the one used by the browser. The latest stable version downloaded is v1.3.0 while if you use npm install handlebars, it will install 2.0.0-alpha4 for you.

Please check it out using

handlebars any_your_template_before_compile.handlebars | grep "compiler"

which will give you like, if you indeed installed handlebar 2.0.0-alpha4:

this.compiler = [5, '>=2.0.0']

With the first number stands for the version for your handlebar compiler. Type in the following code in browser console, see if the result match the version.

Handlebars.COMPILER_REVISION

If you have compiler 5 with browser revison 4, then you will have the above problem.

To fix it, install handlebar 1.3.0 with the following command

npm install handlebars@1.3.0 -g

Then try to compile it again, you will see this time, it gives you matching version info and you are good to go with the precompiled templates.

this.compilerInfo = [4, '>=1.0.0']


Just explain if you have tons of templates:

Firstly externalize each piece of your braced templates: event.handlebars, item.handlebars, etc... You can put them all in one folder, say "/templates"

Compile all the files and concatenate it into 1 file with the following command:

handlebars *.handlebars -f templates.js

And include handlebars.runtime, this file in your HTML

<script src="/lib/handlebars.runtime.js"></script>
<script src="templates.js"></script>

The templates will be injected into Handlebars.templates by their name. For example, event.handlebars can be accessed by Handlebars.tempaltes['event'].

참고URL : https://stackoverflow.com/questions/8659787/using-pre-compiled-templates-with-handlebars-js-jquery-mobile-environment

반응형