codecamp

Harp 内容

使用 Harp,你可以获取到你的编译文件的信息,除了源代码文件的元数据

有时你可能希望将变量分离开来,或者说将所有的全局数据放在一个文件中并非有利。文件元数据来做这件事情是完美的。​_data.json​ 文件比较特别,让数据在模板中可用。

示例

也许你有一个全部是图片的目录,并且希望展示它们全部,你不需要为每一张图片维持一个特别的元数据。

myproject/
  ├ index.jade
  └ images/
      ├ hello-world.jpg     <-- hello world image
      ├ hello-saturn.jpg    <-- hello saturn image
      └ hello-jupiter.jpg   <-- hello jupiter image

使用 EJS

现在,在 index.ejs 文件中,你可以遍历 _contents 变量,引用每一个文件。

<% for(var i in public.images._contents){ %>
  <% var image = public.images._contents[i] %>
  <% if ( image.match(/\b.(jpg|bmp|jpeg|gif|png|tif)\b/gi) ) { %>
        <div>
            <img src="images/<%= image %>" />
        </div>
  <% } %>
<% } %>

结果是如下的 HTML:

<img src="images/hello-world.jpg" />
<img src="images/hello-saturn.jpg" />
<img src="images/hello-jupiter.jpg" />

使用 Jade

现在,在 index.jade 文件中,你可以遍历 _contents 变量,引用每个文件。

for image in public.images._contents
  img(src="images/#{ image }")

结果是下面的 HTML:

<img src="images/hello-world.jpg" />
<img src="images/hello-saturn.jpg" />
<img src="images/hello-jupiter.jpg" />


Harp 元数据
Harp 当前对象
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }