【问题标题】:convert json to markdown and inject into jade using gulp将json转换为markdown并使用gulp注入jade
【发布时间】:2016-10-18 16:44:10
【问题描述】:

目前我知道如何使用 gulp 将 json 数据注入到 jam 中,但是我的 json 数据中的 markdown 格式不正确。我听说过marked,但不确定如何在我的 gulp 文件或jade 文件中使用它。

我直接使用管道数据

.pipe(data(JSON.parse(fs.readFileSync(file)))
.pipe(pug())
.pipe(gulp.dest(destdir))

我试过了

.pipe(data(marked(JSON.parse(fs.readFileSync(file)))))

.pipe(marked(data(JSON.parse(fs.readFileSync(file)))))

都说 TypeError: src.replace is not a function

我不确定如何将marked 嵌入此处或我的玉代码中。有什么建议吗?

已编辑 因此,我对从JSON.parse 获得的 json 对象进行了一些预处理。在注入我的玉数据之前,我首先为每个 json 对象中的字符串 marked 编写了一个函数。比如:

 var marked = require("marked")
 function preprocess(){
     var data = JSON.parse(fs.readFileSync(file));
     iterate through data and do marked(string)
     return data
 }

现在我可以将渲染的字符串转换成jade,但是jade无法理解markdown符号,例如<p> </p>在我的网页中按字面意思显示为<p> </p>。有什么解决方法吗?

【问题讨论】:

    标签: json gulp pug markdown


    【解决方案1】:

    由于我之前没有直接使用过像您这样的工作流程,因此我无法通过一个建议直接解决您的问题,但我会尝试分享一些组合应用时可能会解决您问题的事情。

    让我们从 Markdown 开始。您可以将 ma​​rkedgulp-markdown-to-json 一起使用。一个常见的工作流程如下所示:

    const gulp = require('gulp');
    const markdownToJSON = require('gulp-markdown-to-json');
    const marked = require('marked');
    
    marked.setOptions({
      pedantic: true,
      smartypants: true
    });
    
    gulp.task('markdown', () => {
      gulp.src('./content/**/*.md')
        .pipe(markdownToJSON(marked))
        .pipe(gulp.dest('.'))
    });
    

    这将获取您的降价并将其包装为 JSON 格式,同时将降价的正文转换为 HTML。如果您查看标记的选项,可以使用一些方法来清理您的降价。它们可能很有用,因为您说您的格式存在问题。

    现在我们有了一个 JSON 文件,我们需要将其通过管道传输到 Jade。您还可以使用 data(locals) 通过 Jade 编译任务进行管道传输。

    gulp.task('compilePug', function() {
        return gulp.src('templates/**/*.pug')
            .pipe(pug({
                pretty: true,
                data: {
                    'posts' : JSON.parse(fs.readFileSync('content/json/content.json'))
                }
            })) 
            .on('error', onError)
            .pipe(gulp.dest('./')); 
    });
    

    编译后,您将可以访问 Jade 中 posts 变量下的 JSON。

    最后,您提到段落标签出现在您的 Jade 模板中。听起来您正试图将纯 HTML 传输到 Jade。这很好,事实上,如果您使用我在开始时分享的 gulp 工作流程,您将通过管道将 HTML 传输到 Jade。你只需要告诉 Jade HTML 即将到来:

    !{posts.HTMLfromJSON} // Jade will expect HTML
    #{posts.HTMLfromJson} // Jade won't expect HTML it will treat it like plain text
    

    希望这些方法能帮助您解决问题。

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 1970-01-01
      • 2019-03-10
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 2016-04-05
      相关资源
      最近更新 更多