akornatskyy / wheezy.template

A lightweight template library.
https://wheezytemplate.readthedocs.io/en/latest/
MIT License
29 stars 8 forks source link

Request: convenience for ingesting a top-level JSON array as context #111

Open AndydeCleyre opened 5 days ago

AndydeCleyre commented 5 days ago

Hello, and thanks again for this excellent tool! I still use its CLI all the time.

Sometimes I get JSON output from another command that I want to use as the context/variables for a wheezy template, and that JSON happens to be in the form of an array, rather than a dict/map. So I do some shell work to wrap the JSON array in a one-key dict, with the array as its value.

Here's an example (Zsh):

template=(
    '@require(_)'
    '@for pkg in _:'
        '@if pkg["name"] not in ("setuptools", "six", "pip", "pip-tools"):'
            '@pkg["name"]'
            '@pkg["version"]'
            '@pkg["latest_version"]'
        '@end'
    '@end'
)
cells=($(
    wheezy.template =(<<<${(F)template}) \
    =(<<<"{\"_\": $(pip list --outdated --format=json)}")
))

Might it make sense to offer some way on the wheezy side of things to @require a top-level array as context?

akornatskyy commented 5 days ago

cli contexts passed are available as the __args__ list variable in version 3.2.3. in your case that would be:

@require(__args__)
@for pkg in __args__[0]:
    @if pkg["name"] not in ("setuptools", "six", "pip", "pip-tools"):
        @pkg["name"]
        @pkg["version"]
        @pkg["latest_version"]
    @end'
@end

the passed context must be a valid json, e.g. strings need to use double quotes, etc.

AndydeCleyre commented 5 days ago

Oh, great, thank you! I didn't find this in the docs and didn't see any release notes. I'll be sure to use this!

I'm happy to see this issue closed, since what I sought is already available.


EDIT: Oh! I didn't realize this release was just hours ago, and that you added this feature in response to this issue. Thanks so much!

AndydeCleyre commented 3 days ago

With this feature I'm now trying out a nice Zsh function to use wheezy.template similarly to jq or jello:

# Pipe JSON to it, and provide template content as args.
# @j is the JSON. Examples:
#   <pyrightconfig.json wz '@j["venvPath"] is the parent path and @j["venv"] is the folder'
#   <pyrightconfig.json wz '@(print(dumps(j)))'
wz () {  # <template line>...
  emulate -L zsh
  local tmpl=(
    '@require(__args__)'
    '@(j=__args__[0])\'
    '@(from json import dumps)\'
    $@
  )
  wheezy.template =(<<<${(F)tmpl}) =(<&0)
}