noahmorrison / chevron

A Python implementation of mustache
MIT License
505 stars 55 forks source link

Support custom python object serialization #108

Open tzoiker opened 2 years ago

tzoiker commented 2 years ago

Due to security issues we decided to migrate from jinja to mustache and faced some problems with writing custom lambdas. Adding custom serialization of python objects would help a lot.

Toy example, on what is impossible to elegantly achieve now.

Complete example of what we want to achieve:

import fast_json
from datetime import datetime
import chevron

def format_dt(text, render):
    params = fast_json.loads(render(text))
    dt = datetime.fromisoformat(params['dt'])
    return dt.strftime(params['format'])

chevron.render(
    '{{#format_dt}}{"dt": "{{ data.dt }}", "format": "%d-%m-%Y"}{{/format_dt}}: {{ data }}',
    data={
        'data': {
            'dt': datetime.now(),
            'text': 'text',
        },
        'format_dt': format_dt,
    },
    serializer=fast_json.dumps,
).replace('"', '"')

gives '03-11-2021: {"dt": "2021-11-03T16:05:29.477125", "text": "text"}'

instead of "03-11-2021: {'dt': datetime.datetime(2021, 11, 3, 16, 6, 42, 483261), 'text': 'text'}" without custom serialization.