Skip to content

Instantly share code, notes, and snippets.

@olets
Created September 24, 2021 07:06
Show Gist options
  • Save olets/50e4fda346c0b41f4fc05ab3eb9be7c9 to your computer and use it in GitHub Desktop.
Save olets/50e4fda346c0b41f4fc05ab3eb9be7c9 to your computer and use it in GitHub Desktop.
Twig text transform (case) macros

Twig text transform (case) macros

Macros for

  • camelCase ( camel(string))
  • PascaleCase (pascale(string))
  • snake_case (snake(string))
  • SCREAMING_SNAKE_CASE (screamingsnake(string))

Demo

https://twigfiddle.com/djctym

{% from 'text-transform-macros.twig' import camel, pascale, screamingsnake, snake %}
{{ camel('a-b c') }}
{{ pascale('a-b c') }}
{{ snake('a-b c') }}
{{ screamingsnake('a-b c') }}
{% macro camelHelper(string, delimiterOld, delimiterNew = '') %}
{% set segments = string|trim|split(delimiterOld) -%}
{% set result = segments[0] -%}
{% if segments|length > 1 -%}
{% set result = [result]
|merge(segments[1:]|map(s => s|capitalize))
|join(delimiterNew) -%}
{% endif -%}
{{ result -}}
{% endmacro %}
{% macro camel(string) -%}
{% set result = string -%}
{% set result = _self.camelHelper(result, '-') %}
{% set result = _self.camelHelper(result, ' ') %}
{{ result -}}
{% endmacro %}
{% macro pascale(string) -%}
{% set result = string -%}
{% set result = _self.camelHelper(result, '-') %}
{% set result = _self.camelHelper(result, ' ') %}
{{ result|upper -}}
{% endmacro %}
{% macro snake(string) -%}
{{ string|split('-')|join('_')|split(' ')|join('_') -}}
{% endmacro %}
{% macro screamingsnake(string) -%}
{{ _self.snake(string)|upper -}}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment