fastify/point-of-view

nunjucks custom filter is not working

ashwin31 opened this issue · 1 comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.21.0

Plugin version

3.2.4

Node.js version

18.13.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

20.04

Description

i tried to implement custom filter for nunjucks templates and it resulted in error.

Steps to Reproduce

import path from 'path'
import AutoLoad from '@fastify/autoload'
import { fileURLToPath } from 'url'
import nunjucks from 'nunjucks';

import moment from 'moment';

var env = new nunjucks.Environment();

// const renderer = nunjucks.configure(join(__dirname, 'views'));
const templatesPath = path.join(process.cwd(), 'views'); // Path to your templates folder
const renderer = nunjucks.configure(templatesPath);


env.addFilter('dateformat', function(date) {
  return moment(date).format('MMMM Do YYYY, h:mm:ss a');
});

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// Pass --options via CLI arguments in command to enable these options.
export const options = {}

export default async function (fastify, opts) {
  // Place here your custom code!

  // Do not touch the following lines
  
  // This loads all plugins defined in plugins
  // those should be support plugins that are reused
  // through your application
  fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'plugins'),
    options: Object.assign({}, opts)
  })

  // This loads all plugins defined in routes
  // define your routes in one of these
  fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'routes'),
    options: Object.assign({}, opts)
  })

  // Registering a view engine for Nunjucks
fastify.register(import("@fastify/view"), {
  engine: {
    nunjucks: nunjucks
  },
  includeViewExtension: true,
  templates: templatesPath
});


}

Expected Behavior

No response

tried this too but no use

const renderer = nunjucks.configure(templatesPath);

renderer.addFilter('dateformat', function(date) {
  return moment(date).format('MMMM Do YYYY, h:mm:ss a');
});