1

我想在Pug.js过滤器中绑定一些值。但是该过滤器工作正常,值不绑定。

带过滤器的输出结果

<style>.#{cs_1}{font-family:monospace !important;color:#a1292c !important}.#{cs_1}:hover{background-color:transparent !important;text-decoration:underline !important}.#{cs_2}{position:absolute;font-size:11px;text-transform:none;left:80px;top:12px;border-left:1px solid #ccc;padding-left:6px}.#{cs_3}{white-space:nowrap}</style>

没有过滤器的输出结果

<style>
    .eTWkI {
        font-family: monospace !important;
        color: #a1292c !important;
    }
    .eTWkI:hover {
        background-color: transparent !important;
        text-decoration: underline !important;
    }
    .Rzorr {
        position: absolute;
        font-size: 11px;
        text-transform: none;
        left: 80px;
        top: 12px;
        border-left: 1px solid #ccc;
        padding-left: 6px;
    }
    .vMvwp {
        white-space: nowrap; 
    }
</style>

Pug.js 代码

注意::minifycss使用uglifycss模块制作的过滤器

- var length = 5
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz_-"

- var cs_1 = utils.randomString(length, chars)
- var cs_2 = utils.randomString(length, chars)
- var cs_3 = utils.randomString(length, chars)

style
    :minifycss
        .#{cs_1} {
            font-family: monospace !important;
            color: #a1292c !important;
        }
        .#{cs_1}:hover {
            background-color: transparent !important;
            text-decoration: underline !important;
        }
        .#{cs_2} {
            position: absolute;
            font-size: 11px;
            text-transform: none;
            left: 80px;
            top: 12px;
            border-left: 1px solid #ccc;
            padding-left: 6px;
        }
        .#{cs_3} {
            white-space: nowrap; 
        }

所以过滤器看起来像:

require('pug').filters = {

    minifycss: (text, options) => {
        if (!text) return;
        return uglifycss.processString(text, options);
    }

};
4

1 回答 1

2

看起来 Pug 过滤器是在编译时运行的,并且不允许变量/动态内容。有关更多信息,请参阅此 GitHub 问题。您可以导出minifycss您编写的函数,然后在 Jade 中使用它(就像在这个相关的 GitHub 问题中所做的那样),以使您的过滤器代码正常工作。您需要将该require函数导出到 Pug (locals.require = require在您的路线中),然后使用它minifycss从其他地方请求该函数。

但是,似乎上述问题已在 Pug 2.0.0 beta11 中修复。根据您使用的 Pug 版本,这可能是问题的原因。

于 2017-03-23T22:02:02.603 回答