Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@fiad/twig-addons

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@fiad/twig-addons

A collection of filters and functions for Twig (JS)

latest
Source
npmnpm
Version
1.3.0
Version published
Maintainers
1
Created
Source

@fiad/twig-addons

A collection of filters and functions for Twig (JS)

Get started

Installation

npm i @fiad/twig-addons

Usage

Basic

import twig from 'twig'
import twigAddons from '@fiad/twig-addons'

const engine = twigAddons(twig)

engine.renderFile('path/to/template.twig', { foo: 'bar' }, (err, html) => {
  fs.writeFileSync('path/to/template.html', html)
})

With Express

import express from 'express'
import twig from 'twig'
import twigAddons from '@fiad/twig-addons'

const app = express()

app.engine('twig', twigAddons(twig).__express)

Filters list

map

A porting of JavaScript's Array.prototype.map().

Definition:

map(values, args)
ArgumentDescriptionType
valuesThe original valuesarray
argsThe array of arguments passed to the filterarray

Here below the supported filter arguments:

ArgumentDescriptionType
handlerThe mapping handlerstring

ℹ️ Please note that the handler argument should be a stringified arrow function evaluable by eval().

Usage:

// mock
{
  "guests": [
    { "firstname": "John", "lastname": "Doe", /* ... */ },
    { "firstname": "Jane", "lastname": "Doe", /* ... */ }
  ]
}
<p class="guests">
  {{ guests|map('({ firstname, lastname }) => `${firstname} ${lastname}`')|join(', ') }}
</p>

⚠️ Since this filter involves the usage of eval(), it's recommended to use it for static sites generation purposes only, so that the stringified JavaScript execution will be limited to the development environment. Look here to learn more.

reduce

A porting of JavaScript's Array.prototype.reduce().

Definition:

reduce(values, args)
ArgumentDescriptionType
valuesThe original valuesarray
argsThe array of arguments passed to the filterarray

Here below the supported filter arguments:

ArgumentDescriptionType
reducerThe reducing handlerstring
carryThe initial reduced valueany

ℹ️ Please note that the reducer argument should be a stringified arrow function evaluable by eval().

Usage:

// mock
{
  "cart": [
    { "price": 10, /* ... */ },
    { "price": 20, /* ... */ },
    { "price": 15, /* ... */ }
  ]
}
<p class="total">
  {{ cart|reduce('(total, { price }) => (total + price)', 0) }} €
</p>

⚠️ Since this filter involves the usage of eval(), it's recommended to use it for static sites generation purposes only, so that the stringified JavaScript execution will be limited to the development environment. Look here to learn more.

remap

It allows you to remap an object with different keys and eventually discard its needless properties.

Definition:

remap(value, args)
ArgumentDescription
valueThe original object to be remapped
argsThe array of arguments passed to the filter

Here below the supported filter arguments:

ArgumentDescription
keysThe list of key replacements, formatted like "old:new"
optionsA configuration object containing additional settings

The options argument supports the following properties:

PropertyDescriptionDefault
discardUnmentionedIf true, any properties not included in the keys argument will be omitted from the returned objectfalse

Usage:

Source

// mock
{
  "article_id": "post-1",
  "article_type": "news",
  "article_title": "Lorem ipsum.",
  "article_text": "Ea duis sint ad ipsum in dolor quis consequat.",
  "article_category": "foo"
}
{# components/article.twig #}
<article>
  <h1>{{ title }}</h1>
  <p>{{ description }}</p>
</article>


{# templates/page.twig #}
{% set data = mock|remap([
  'article_title:title',
  'article_text:description'
], {
  discardUnmentioned: true
}) %}

<main>
  {% include 'components/article.twig' with data %}
</main>

Result

<main>
  <article>
    <h1>Lorem ipsum.</h1>
    <p>Ea duis sint ad ipsum in dolor quis consequat.</p>
  </article>
</main>

Functions list

html_classes

A porting of Twig's html_classes. Look at the official documentation to learn more about usage.

Definition:

html_classes(...classes)

tag_attributes

It dynamically builds the stringified attributes list of an html tag starting from a key-value object. It supports you in adopting a standard and comfortable parametric system to pass attributes to a component directly from the include statement.

Definition:

tag_attributes(attributes, defaults)
ArgumentDescription
attributesThe attributes object to be parsed
defaults (optional)The default attributes to extend, useful when you need to merge with some predefined properties (use this argument instead of Twig built-in merge filter to ensure proper attribute parsing)

Usage:

Source

// mock
{
  "link": {
    "label": "Lorem ipsum",
    "attributes": {
      "class": "link--primary",
      "href": "https://domain.ext/slug",
      "target": "_blank"
    }
  }
}
{# components/link.twig #}

{% set defaults = {
  class: 'link',
  target: '_self'
} %}

<a {{ tag_attributes(attributes, defaults) }}>
  <span class="link__label">{{ label }}</span>
</a>

Result

<a class="link link--primary" href="https://domain.ext/slug" target="_blank">
  <span class="link__label">Lorem ipsum</span>
</a>

ℹ️ Please note that the default class attribute wasn't overridden, as did the target one instead, but the default value and the overriding one have been concatenated. This is to avoid the accidental breaking of some of the component basic styles and behaviors associated with the default class(es) eventually defined within the component partial.

Keywords

twig

FAQs

Package last updated on 02 Jan 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts