Angular环境下如何在HTML文件中插入多行原生Pug代码?
在Angular中处理多行Pug代码的方法
嘿,作为刚接触Angular和Pug的新手,我懂你这种找不到方法的困惑!我来帮你分两种情况解决问题——一种是把Pug作为Angular组件的模板来实际渲染内容,另一种是在HTML页面里展示Pug代码示例:
一、把Pug作为Angular组件的模板使用
Angular默认不支持Pug,得先做几步配置才能用:
- 先安装依赖包
打开终端,在项目根目录运行:
npm install pug pug-loader --save-dev
- 配置Angular CLI(修改
angular.json)
找到你项目对应的配置项,在projects -> [你的项目名] -> architect -> build -> options和projects -> [你的项目名] -> architect -> test -> options里,添加模板加载配置:
"template": { "loader": "pug-loader" }
- 编写组件和Pug模板
- 在组件的
.ts文件里定义数据:
import { Component } from '@angular/core'; @Component({ selector: 'app-card-container', templateUrl: './card-container.pug', // 这里指定Pug文件作为模板 styleUrls: ['./card-container.scss'] }) export class CardContainerComponent { // 你的卡片数据 cards = [ { title: 'Mountain View', copy: 'Check out all of these gorgeous mountain trips with beautiful views of, you guessed it, the mountains', button: 'View Trips' }, { title: 'To The Beach', copy: 'Plan your next beach trip with these fabulous destinations', button: 'View Trips' }, { title: 'Desert Destinations', copy: 'It\'s the desert you\'ve always dreamed of', button: 'Book Now' }, { title: 'Explore The Galaxy', copy: 'Seriously, straight up, just blast off into outer space today', button: 'Book Now' } ]; }
- 创建对应的
card-container.pug文件,写入你的Pug代码:
//- 定义卡片mixin mixin card(title, copy, button) .card .content h2.title= title p.copy= copy button.btn= button //- 渲染所有卡片 main.page-content each card in cards +card(card.title, card.copy, card.button)
这样运行Angular项目后,组件就会用Pug模板渲染出对应的卡片啦!
二、在HTML文件中展示多行Pug代码(作为示例)
如果你只是想在页面上展示Pug代码片段,不用它渲染内容,可以这么做:
- 在组件的
.ts文件里把Pug代码定义成字符串:
import { Component } from '@angular/core'; @Component({ selector: 'app-code-demo', templateUrl: './code-demo.component.html', }) export class CodeDemoComponent { pugCode = `var cards = [{ title: 'Mountain View', copy: 'Check out all of these gorgeous mountain trips with beautiful views of, you guessed it, the mountains', button: 'View Trips' }, { title: 'To The Beach', copy: 'Plan your next beach trip with these fabulous destinations', button: 'View Trips' }, { title: 'Desert Destinations', copy: 'It\\'s the desert you\\'ve always dreamed of', button: 'Book Now' }, { title: 'Explore The Galaxy', copy: 'Seriously, straight up, just blast off into outer space today', button: 'Book Now' }] mixin card(title, copy, button) .card .content h2.title= title p.copy= copy button.btn= button main.page-content each card in cards +card(card.title, card.copy, card.button)`; }
- 在组件的
.html文件里用<pre>和<code>标签展示,用[innerText]绑定避免HTML解析问题:
<pre><code [innerText]="pugCode"></code></pre>
这样页面上就会完整显示你的多行Pug代码了。
内容的提问来源于stack exchange,提问作者kEN Rowdy
相关产品推荐
相关产品推荐

