在 Laravel Blade 中使用 AngularJS
说明
Laravel 的 Blade 模版引擎和 AngularJS 的模版引擎使用同样的变量显示方法如下:
{{ variableName }}
解决方法
下面几种解决方法:
- 修改 Laravel Blade 的变量解析方式;
- 修改 AngularJS 的变量解析方式;
- 在 Blade 里使用
@{{ variableName }}
, 跳过 Blade 的变量解析; - 在 Blade 模版里面使用
include
去包含 Angular 模版 (推荐这种方法); - 完全不使用 Blade.
1. 修改 Laravel Blade 的变量解析方式
使用以下方法修改:
Blade::setContentTags('<%', '%>'); // for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>'); // for escaped data
上面的修改会影响 Blade 模版引擎的行为:
- 变量使用输出 - <% $variable %>
- 注释 <%-- $variable --%>
- 需要转义的变量数据 <%% $variable %%>
代码可以放到
routes.php
文件里面.
2. 修改 AngularJS 的变量解析方式
在初始化 Module
的时候, 调用 $interpolateProvider
进行设置:
var sampleApp = angular.module('sampleApp', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
上面的代码会让 AngularJS 使用 <% variableName %>
这种方法去解析变量.
3. 在 Blade 里使用 @{{ variableName }}
, 跳过 Blade 的变量解析
在写变量的时候, 可以使用在前面加 @
的方法跳过解析:
@{{ variableName }}
上面的代码你如果写在 Blade 模版里面的话, 应用输出 HTML 会是:
{{ variableName }}
4. 在 Blade 模版里面使用 include
去包含 Angular 模版 (推荐这种方法)
如以下代码, 是在文件 app/views/index.blade.php
Blade 模版里面, 注意看 @include
的使用:
<!doctype html>
<html>
<head>
<title>Fancy Laravel and Angular</title>
<!-- load angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
</head>
<body>
@include('angular-stuff'); <!-- app/views/angular-stuff.php -->
</body>
</html>
使用 @include('angular-stuff')
会加载 app/views/angular-stuff.php
文件.
推荐使用此方法, 原因是能够让代码更加模块化, 并且能同时兼并 Laravel Blade 和 Angular 的好处.
5. 完全不使用 Blade.
完全的把 Laravel App 作为 API 服务器, 前端和后端分离.
// app/routes.php
Route::get('/', function() {
return View::make('index'); // app/views/index.php
});
推荐文章: