purcell / airspeed

A lightweight Python template engine compatible with Velocity, used in OpenStack
Other
91 stars 37 forks source link

Missing support for keySet() and toString()? #47

Open halfdanrump opened 4 years ago

purcell commented 4 years ago

You could add support for keySet here with a couple of tests. I'm not sure that we should be trying to make airspeed mimic Java too much, though, and if your Velocity templates use toString() a lot, they would probably need to be changed for Airspeed anyway. Can't really comment on your use-case for that specifically.

halfdanrump commented 4 years ago

Thanks for replying! @purcell

I think I was a little hasty with the keySet(). I found out that iterating over a dict by default iterates over the keys:

data = dict(a='2', b='3')
template = airspeed.Template("""
#foreach( $key in $data )
  key: $key
  data: $data[$key]
#end
""")
print(template.merge(locals()))

output:

  key: a
  data: 2

  key: b
  data: 3

which is exactly what I need.

as for toString I need to convert an array [1, 2, 3] into a string ('1', '2', '3'). There might be other ways to do this.

I'm using Airspeed to develop templates for a web application that renders the templates with Java, hence I need to stay as close to the original templating language as possible if that makes sense?

purcell commented 4 years ago

as for toString I need to convert an array [1, 2, 3] into a string ('1', '2', '3'). There might be other ways to do this.

Yeah, I think if you need the output string to look exactly like that, that's quite a specific thing to expect of Airspeed. For things like that, you can provide formatting functions in the rendering context, e.g. formatArray, and then implement them differently on both platforms. Or, have a little set of macros that you include in the templates, and then use slightly different implementations under Java and Python.