stencilproject / Stencil

Stencil is a simple and powerful template language for Swift.
https://stencil.fuller.li
BSD 2-Clause "Simplified" License
2.34k stars 221 forks source link

Added filter to apply dynamic filters #203

Closed ilyapuchka closed 5 years ago

ilyapuchka commented 6 years ago

filter:arg will resolve its argument as filter expression which will allow to apply dynamic filters.

The use case for that can be using Sourcery to generated code for Codable protocols and use different key coding strategies applied for different data models. It will allow to specify strategy as one of Stencil filters in a type annotation, i.e. uppercaseFirstLetter or camelCaseToSnakeCase, or even filter with arguments.

Currently in template I have to check annotations against hardcoded set of filters to be able to apply them. With this change this template code

{% if strategy == "upperFirstLetter" %}{{ variable.name|replace:"_",""|upperFirstLetter }}{% else %}{{ variable.name|replace:"_",""|camelToSnakeCase }}{% endif %}

becomes this

{{ variable.name|replace:"_",""|filter:strategy }}

and allows to use any registered filter without changing anything in template.

AliSoftware commented 6 years ago

I'll have to re-check the Stencil docs (on phone rn so not the best device to read them) but I thought Stencil already had a {% filter xx %}…{% endfilter %} tag that would also allow you to do dynamic filters already?

AliSoftware commented 6 years ago

My bad, nvm, that tag indeed already exists but expects a filter name not a variable so isn't able to do dynamic filters. Forget I said anything

ilyapuchka commented 6 years ago

@AliSoftware the implementation of filter node only converts the whole node to filter expression applied to the rendered content of the node, it does not resolve the name of the filter as variable. But that's something we can add too! Also I just find filter expression easier to use than filter node and better composable (chaining vs nesting)

djbe commented 6 years ago

Except from the small changelog change, and some small access questions, this LGTM.

djbe commented 6 years ago

Before I forget: This PR should document the changes in the docs.

ilyapuchka commented 5 years ago

@djbe comments addressed

djbe commented 5 years ago

This will need a rebase, based on 0.12. Be careful when rebasing the changelog, as the entry will need to be moved to the right section (under master).

ilyapuchka commented 5 years ago

@djbe I updated docs. We'll need this, in particular making Expression type public to add support for {% call this if condition else that %} in StencilSwiftKit, unless we move call node into Stencil.

djbe commented 5 years ago

Looks GTM. How come this branch is till out-of-date after that merge you did one hour ago?

ilyapuchka commented 5 years ago

🤷‍♂️