如何在 twing 中创建新过滤器

问题描述 投票:0回答:1

我正在使用以下代码在

twig

中创建一个新过滤器
const twig = require("twig");

twig.extendFilter("date_format", (value) => {
  return value ? dateFNS.format(value.unixUTC, "MM/dd/yyyy") : null;
});

同样,我们如何在

twing
中创建新的过滤器?

我尝试过以下方法

const { TwingFilter, TwingEnvironment, TwingLoaderFilesystem } = require("twing");
const format_date = new TwingFilter("format_date", (value) => {
    return value ? dateFNS.format(value.unixUTC, "MM/dd/yyyy") : null;
});
const loader = new TwingLoaderFilesystem([
    "./screen"
]);
const twing = new TwingEnvironment(loader);
twing.addFilter(format_date);

但是出现以下错误

TypeError: callable.apply(...).catch is not a function

express twig twing
1个回答
0
投票

Twing v7.0.0

我知道这是一个老问题,但我刚刚为 Twing v7.0.0 创建一个自定义过滤器,所以希望这对某人有帮助。

import { createArrayLoader, createEnvironment, createFilter, TwingCallable, TwingCallableArgument, TwingEnvironment, TwingFilter } from 'twing';
import * as dateFns from 'date-fns';

/* Set up a basic environment */
const loader = createArrayLoader({
  'format.twig': '{{ date|format_date }}',
  'override-format.twig': '{{ date|format_date("yyyy") }}',
});
const environment: TwingEnvironment = createEnvironment(loader);

/* Add an optional argument for the format */
const acceptedArguments: TwingCallableArgument[] = [{ name: 'format', defaultValue: 'MM/dd/yyyy' }];

/* Create a TwingCallable function to act as our filter */
const formatDate: TwingCallable = async (_executionContext, value: Date, format: string) => {
  return value ? dateFns.format(value, format) : null;
};

/* Create the filter with the name format_date */
const formatDateFilter: TwingFilter = createFilter('format_date', formatDate, acceptedArguments);

/* Add the filter to our twig environment */
environment.addFilter(formatDateFilter);

environment
  .render('format.twig', {
    date: new Date(),
  })
  .then((result) => {
    console.log(result);
  });
© www.soinside.com 2019 - 2024. All rights reserved.