LoginSignup
3
3

More than 5 years have passed since last update.

Jinja2とAngularJSの変数スコープの競合を解決する方法

Last updated at Posted at 2015-01-04

AngularJS と Jinja2 は HTML に変数スコープを {{...}} という二重の波括弧で囲う構文仕様になっています。よって、 Python のフレームワークで使われる Jinja2 で AngularJS を書きたい場合に HTML に AngularJS の変数スコープを書くと競合してしまい, AngularJS の変数スコープは無効化されてしまいます。

AngularJS側の変数スコープのデリミタ({{...}})を変更する方法はnaoiwataさんのエントリーでみつかったのですが、Jinja2側を変更したい場合のやり方がわからなかったので調べてみた。

・・・で結論。

最初の環境設定
variable_start_stringvariable_end_stringを変更をすればいいらしい。

というわけでGAEのwebapp2フレームワークからJinja2のテンプレートエンジンを使うスクリプトを書いてみた。

index.py
import os
import webapp2
import jinja2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__))
    ,extensions=['jinja2.ext.autoescape']
    ,variable_start_string='[['
    ,variable_end_string=']]'
   ,autoescape=True)

class MainPage(webapp2.RequestHandler):

    def get(self):
        template_values = {
            'test': 'hello Jinja2'
        }

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))

app = webapp2.WSGIApplication([('/', MainPage)],
                              debug=True)

※webapp2でJinja2を使う方法はココを参照。

index.html
<!DOCTYPE html>
<html ng-app="MyApp">

  <head>
    <script src="https://code.angularjs.org/1.3.5/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="mainCtrl">
      <p>{{test}}</p>
      <p>[[test]]</p>
    </div>
  </body>

</html>
script.js
var myModule = angular.module("MyApp", []);
myModule.controller('mainCtrl',['$scope', function($scope){
  $scope.test = "hello angularjs";
}]);

うまくいくとブラウザ上でhello angularjshello Jinja2が表示されます。

GAEにアップロードすればappspot.com上でAngularjsが使えるようになります。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3