tera icon indicating copy to clipboard operation
tera copied to clipboard

Strip template

Open peter-oneill opened this issue 2 years ago • 1 comments

I have a usecase for tera which can be solved by tera providing a "strip" function which strips any tera-rendered sections, leaving the user with only the basic text elements of the template (and TBD any { raw } contents). Detail on the specific usecase at the bottom, for interest.

Example

input template:

arg1: true

{% filter upper %}
args-to-be-stripped:
    - Hello
    - World
{% endfilter %}

{ raw }
arg2: false
{ endraw }

stripped output:

arg1: true


arg2: false

There are a couple of ways I've tried doing this:

  1. No tera changes: Handle the stripping in the calling code. This relies upon accessing the AST to find the original template's Node::text and Node::raw elements, which isn't a stable API
  2. Implement the same in tera - provide a stable "strip" interface which does much the same internally, but avoids relying on the AST over the public interface

I'd prefer 2) for my calling code, as it doesn't rely on an unstable, not-truly-public API. Would you be receptive to a PR with that addition?

The other possibility is for a more flexible API, where the user can specific which elements to render/strip (and my case would be covered by the user specifying 'text' and 'raw'), but again this exposes the AST as a public API.

Addendum:

My specific case is a yaml file which relies on values loaded from another file 'variables.yml'. This can't be rendered until variables.yml exists, which it may not do at start of day. The yaml file can also provide hooks for commands to be executed before the loaded values are needed. By providing a "strip" function, the calling code can do the following sequence:

  1. strip any tera templated function from the template
  2. parse as yaml to extract the pre-render hook
  3. run the hook (creating a variables file if needed)
  4. render the original template using tera (which now succeeds because the variables file exists)
  5. (continue processing)

peter-oneill avatar Sep 05 '23 18:09 peter-oneill

I don't think that would be added and there is no more AST in the upcoming v2

Keats avatar Sep 08 '23 08:09 Keats