LoginSignup
35
35

More than 5 years have passed since last update.

Laravel(blade template)でvue.jsのmustache記法を使用する

Last updated at Posted at 2015-03-23

laravelアプリケーションを作成する際、viewにはblade templateが使用されています。bladeでのdataの出力では"{{}}"が使用されており、bladeテンプレート内で普通にmustache記法を使用すると競合してしまい、ErrorExceptionになるか、予測していない情報が表示されたりしてしまいます。ということで2つ対応方法をご紹介。

vue.jsのmustache記法に使用する記号を変更する("{{}}"を別の記号にする)

vue.jsドキュメントGlobal APIのVue.configに"delimiters" という設定があります。

Vue.config
{
  // print stack trace for warnings?
  debug: true,
  // attribute prefix for directives
  prefix: 'v-',
  // interpolation delimiters
  // for HTML interpolations, add
  // 1 extra outer-most character.
  delimiters: ['{{', '}}'],
  // suppress warnings?
  silent: false,
  // interpolate mustache bindings?
  interpolate: true,
  // use async updates (for directives & watchers)?
  async: true,
  // allow altering observed Array's prototype chain?
  proto: true
}

たとえば"{{}}"を"(%%)"の様な書き方に変更する場合は"new Vue()"を実行する前にconfigを変更します。

example.js
Vue.config.delimiters = ['(%', '%)'];
var vm = new Vue({
    el: '#myApp',
    data: {
        username: 'hogehoge'
    }
});
example.blade.php
<div id="myApp">
    <p>(%username%)</p>
</div>

blade template内で"{{}}"の前に"@"を付ける

blade templateでは"{{}}"の前に"@"を付けると"{{}}"をそのまま出力することが出来ます。

Blade Templatingの「Displaying Raw Text With Curly Braces」に書かれています。

example.blade.php
@{{ This will not be processed by Blade }}

こうすれば"{{}}"が直接出力されるのでErrorExceptionは発生しません。


ちなみに今回は前者を採用しました。後者であればconfigを変更せずに使用できるのですが、正直ごちゃってくる可能性が大いにあったので、そこはちゃんと住み分けて使用する方がいいと考えたからです。blade template側の設定を変える方法もあると思いますが、今回はあくまでlaravelアプリケーションに対してVue.jsを使用したかったので、Vue.js側のconfigを変更しました。

意外とまだまだ日本での実績は少ないみたいですので、これからもっと使ってみたいですね。

35
35
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
35
35