askama icon indicating copy to clipboard operation
askama copied to clipboard

Add support for pattern matching on slices

Open linabutler opened this issue 4 years ago • 2 comments

Hi! 👋 I love Askama's pattern-matching syntax, with match-when-else. Would you be open to extending it to support the newly-stabilized subslice patterns, too? It would help when matching against a vector or a slice, if you want different output for zero, one, or multiple elements.

Here's a recent, real-life example of where I would've loved to have this, for generating Swift code in a template (the syntax could definitely use more work; it's just a placeholder):

{%- match func.arguments() -%}
  {%- when [] %}
    public func {{ func.name() }}() { /* ... */ }
  {% when [] with (arg) -%}
    {# Don't generate argument labels for single-argument functions #}
    public func {{ func.name() }}(_ {{ arg.name() }} {{ arg.type() }}) { /* ... */ }
  {% when [] with (args) -%}
    public func {{ func.name() }}(
      {%- for arg in args %}
      {{ arg.name() }}: {{ arg.name() }} {{ arg.type() }}{% if loop.last %}{% else %},{% endif %}
      {%- endfor %}
{%- endmatch %}

Thanks!

linabutler avatar Jun 26 '20 19:06 linabutler

Sure! The pattern-matching code is kind of rough, so this would just be one of many things about it we could fix.

Is this usage actually for a Mozilla project, or a personal project of yours? Always love to hear about use cases!

For the parser code, maybe start here; for the code generator, here.

djc avatar Jun 27 '20 18:06 djc