• Stars
    star
    153
  • Rank 235,710 (Top 5 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Code formatting plugin for Prettier which can handle Twig/Melody templates

Prettier for Melody

Prettier Banner


This Plugin enables Prettier to format .twig files, as well as .html.twig and .melody.twig. Melody is a component based UI framework that uses Twig as its template language.

Install

yarn add --dev prettier-plugin-twig-melody

Use

prettier --write "**/*.melody.twig"

In your editor, if the plugin is not automatically picked up and invoked (e.g., if you are using format on save, but no formatting is happening when you save), try adding the plugin explicitly in your Prettier configuration (e.g., .prettierrc.json) using the plugins key:

{
    "printWidth": 80,
    "tabWidth": 4,
    "plugins": ["./node_modules/prettier-plugin-twig-melody"]
}

Options

This Prettier plugin comes with some options that you can add to your Prettier configuration (e.g., prettierrc.json).

twigSingleQuote (default: true)

Values can be true or false. If true, single quotes will be used for string literals in Twig files.

twigMelodyPlugins (default: [])

An array containing file paths to plugin directories. This can be used to add your own printers and parser extensions.

The paths are relative paths, seen from the project root. Example:

"twigMelodyPlugins": ["src-js/some-melody-plugin", "src-js/some-other-plugin"]

twigPrintWidth (default: 80)

Because Twig files might have a lot of nesting, it can be useful to define a separate print width for Twig files. This can be done with this option. If it is not set, the standard printWidth option is used.

twigAlwaysBreakObjects (default: false)

If set to true, objects will always be wrapped/broken, even if they would fit on one line:

<section
    class="{{ {
    base: css.prices
} | classes }}"
></section>

If set to false (default value), this would be printed as:

<section class="{{ { base: css.prices } | classes }}"></section>

twigFollowOfficialCodingStandards (default: true)

Follow the standards described in https://twig.symfony.com/doc/2.x/coding_standards.html exactly. If set to false, some slight deviations might occur, such as spaces around the filter | operator (s | upper instead of s|upper).

twigOutputEndblockName (default: false)

Choose whether to output the block name in {% endblock %} tags (e.g., {% endblock content %}) or not. The default is not to output it.

twigMultiTags (default: [])

An array of coherent sequences of non-standard Twig tags that should be treated as belonging together. Example (inspired by Craft CMS):

twigMultiTags: [
    "nav,endnav",
    "switch,case,default,endswitch",
    "ifchildren,endifchildren",
    "cache,endcache"
]

Looking at the case of nav,endnav, this means that the Twig tags {% nav %} and {% endnav %} will be treated as a pair, and everything in between will be indented:

{% nav entry in entries %}
    <li>
        <a href="{{ entry.url }}">{{ entry.title }}</a>
    </li>
{% endnav %}

If we did not list the "nav,endnav" entry in twigMultiTags, this code example would be printed without indentation, because {% nav %} and {% endnav %} would be treated as unrelated, individual Twig tags:

{% nav entry in entries %}
<li>
    <a href="{{ entry.url }}">{{ entry.title }}</a>
</li>
{% endnav %}

Note that the order matters: It has to be "nav,endnav", and it must not be "endnav,nav". In general, the first and the last tag name matter. In the case of "switch,case,default,endswitch", the order of case and default does not matter. However, switch has to come first, and endswitch has to come last.

Features

prettier-ignore and prettier-ignore-start

When you are not happy with how Prettier formats a certain element or section in the code, you can tell it to leave it in peace:

{# prettier-ignore #}
<div   class="weird-formatting"   >This will not be re-formatted</div>

<div   class="weird-formatting"   >But this will be</div>

You can also tell Prettier to leave entire regions as they are:

{# prettier-ignore-start #}
    ...
{# prettier-ignore-end #}

Plugins

Melody features an extensible parser, so chances are you add custom elements for which the parsing and printing logic is not part of this Prettier plugin. Therefore, this Prettier plugin is itself pluggable.

Let's look at an example of a plugin to the plugin:

const melodyIconPlugin = require("../melody-plugin-icon-tag");

const printIconTag = (node, path, print, options) => {
    // Implementation of printing
    // ...
};

module.exports = {
    melodyExtensions: [melodyIconPlugin],
    printers: {
        IconTag: printIconTag
    }
};

As we can see, a plugin to the plugin exports two fields:

  • melodyExtensions: A list of extensions to the Melody framework that might export tags, visitors, functionMap and the like. Usually, such an extension will add additional parsing functionality to the core parser.
  • printers: The Prettier printing functionality for your additional language constructs, tags, operators, etc. This is an object where the keys are the node types in the Melody AST (abstract syntax tree) β€” as retrieved through node.constructor.name β€”, and the values are the print functions with the standard Prettier signature.

Don't forget to make your plugins known through the twigMelodyPlugins option in your Prettier configuration.

Testing

  • You can call yarn testto test against all regular tests

More Repositories

1

prettier-plugin-sort-imports

A prettier plugin to sort imports in typescript and javascript files by the provided RegEx order.
TypeScript
2,939
star
2

parallel-webpack

Builds multi-config webpack projects in parallel
JavaScript
1,484
star
3

gollum

An n:m message multiplexer written in Go
Go
935
star
4

Heimdallr.swift

Easy to use OAuth 2 library for iOS, written in Swift.
Swift
636
star
5

Heimdall.droid

Easy to use OAuth 2 library for Android by trivago.
Kotlin
257
star
6

cluecumber

Clear and concise reporting for the Cucumber BDD JSON format.
Java
254
star
7

melody

Melody is a library for building JavaScript web applications.
JavaScript
215
star
8

Dobby

Swift helpers for mocking and stubbing
Swift
165
star
9

cucable-plugin

Maven plugin that simplifies running Cucumber Scenarios in parallel.
Java
112
star
10

triava

The triava project contains several of trivago's core libraries for Java-based projects: caching, collections, annotations, concurrency libraries and more.
Java
74
star
11

scalad

Horizontal Job Autoscaler for Nomad
Go
69
star
12

tgo

trivago go utilities
Go
57
star
13

hamara

Export datasource from the existing Grafana DB into a YAML provisioning file
Go
56
star
14

jade

A simple but yet powerful library to expose your entities through JSON API.
PHP
55
star
15

nomad-pot-driver

Nomad task driver for launching freebsd jails.
Go
54
star
16

Protector

A circuit breaker for InfluxDB
Python
48
star
17

fastutil-concurrent-wrapper

Set of concurrent wrappers around fastutil primitive maps
Java
32
star
18

babel-plugin-cloudinary

Compile cloudinary URLs at build time.
JavaScript
24
star
19

pbf-loader

Webpack loader for .proto files to be used within mapbox/pbf
JavaScript
21
star
20

rumi

trivago continuous integration executor
PHP
20
star
21

influxdbviewer

JavaScript
18
star
22

samsa

A high level NodeJS stream processing library
TypeScript
18
star
23

preact-hooks-testing-library

preact port of https://github.com/testing-library/react-hooks-testing-library
TypeScript
18
star
24

project-ironman

CSS skeleton / structure we used at trivago for our large scale refactoring project called Project Ironman
CSS
17
star
25

logstash-codec-protobuf

Protobuf codec for parsing data into logstash
17
star
26

jcha

Java Class Histogram Analyser
Java
17
star
27

grok

simple library to use/parse grok patterns with go (100%)
Go
15
star
28

reportoire

Kotlin
15
star
29

ReactiveHeimdall

Reactive wrapper around Heimdall.swift
Swift
14
star
30

chapi

chronos & marathon console client - Manage your jobs like a git repository
PHP
14
star
31

hive-lambda-sting

A small library of hive UDFS using Macros to process and manipulate complex types
Java
14
star
32

rebase

A small python library to make your data layer more robust.
Python
13
star
33

Mail-Pigeon

Mail Pigeon is a mail delivery plattform, which was created in the trivago developer days (something like the Google 20% rule) to replace some of the PHP based mailing scripts that were present that days. trivago has a lot of customers and therefore the focus laid on the fast and relyable sending process of a future mail tool. We decided to build a plattform that just can send mails in a performant manner, later on we built mail pigeon on top of it.
Java
13
star
34

boerewors

Release framework based on Python
Python
11
star
35

rtl-scss-kit

A right-to-left mixin set to create right-to-left and left-to-right css out of one scss-source
CSS
8
star
36

svn-daemon

A daemon to control a svn checkout via a web interface, written in go.
Go
8
star
37

triversity

trivago's university collaboration tool
Vue
7
star
38

exporter-edgecast

A Prometheus exporter for the Edgecast CDN
Go
7
star
39

junior-java-software-engineer-casestudy

Case study for Junior Software Engineer - Java Backend Services
7
star
40

libvips-mozjpeg-amazonlinux-buildscript

Modified libvips build script which helps to build libvips with mozjpeg support on AWS 'AmazonLinux' EC2 instances.
Shell
7
star
41

exporter-chinacache

A Prometheus exporter for the Chinacache CDN
Go
5
star
42

express-booking-selfconnect-api

trivago Express Booking - Self Connect API
PHP
5
star
43

recsys-challenge-2019-benchmarks

Run benchmark algorithms on the data sets of the RecSys Challenge 2019. https://recsys.trivago.cloud/
Python
4
star
44

create-melody-app

Create Melody apps quickly from the command line.
JavaScript
3
star
45

oauth-sdk-js

A tiny javascript library that allows to log in/register with trivago
JavaScript
2
star
46

melody-web

Public web site of the Melody JavaScript framework
HTML
2
star
47

.github

@trivago organization
2
star
48

intellij-idea-plugin

Internal IntelliJ plugin by trivago. Quick and dirty implementation.
Kotlin
1
star
49

melody-template

Melody Starter Example
JavaScript
1
star
50

mod_whatkilledus

Copy of sources from https://emptyhammock.com/projects/httpd/diag/
C
1
star
51

TriMamba

Collection of tools aimed to gather event information from different sources into a database
JavaScript
1
star
52

trivago-gtm-template

GTM template implementation for the trivago Conversion API
Smarty
1
star