0

According to the StringTemplate 4 wiki, I should be able to display an expr property, but I cannot. I'm using StringTemplate4 with jython.

Here's my template file, test.st:

test(persons, person) ::= <<
<table>
    <tr><th>Name</th><th>Age</th></tr>
    <tr><td>$person.name$</td><td>$person.age$</td></tr>
    $persons:{p|<tr><td>$p.name$</td><td>$p.age$</td></tr>}$
</table>

Here's my jython code. When I try to render the template, the name and age values are not shown.

>>> import org.stringtemplate.v4 as st
>>> 
>>> class Person:
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
... 
>>> group = st.STGroupDir('~/template', '$', '$')
>>> tmpl = group.getInstanceOf('test')
>>> 
>>> tmpl.add('persons', [Person('jim', 25), Person('sam', 46)])
/test()
>>> tmpl.add('person', Person('bob', 55))
/test()
>>> 
>>> print tmpl.render()
<table>
    <tr><th>Name</th><th>Age</th></tr>
    <tr><td></td><td></td></tr>
    <tr><td></td><td></td></tr><tr><td></td><td></td></tr>
</table>

In the interpreter, I can access the attributes in tmpl fine.

>>> tmpl.attributes
{person=<__main__.Person instance at 0x54>, persons=[<__main__.Person instance at 0x55>, <__main__.Person instance at 0x56>]}
>>> p = tmpl.getAttribute('person')       
>>> print p.name, p.age
bob 55
>>> for p in tmpl.getAttribute('persons'):
...     print p.name, p.age
... 
jim 25
sam 46

Any idea why this doesn't work? Am I doing something wrong? I also tried creating getName() and getAge() methods for the Person class without luck. If I create a data aggregate I'm able to access the properties fine.

MD6380
  • 1,007
  • 4
  • 13
  • 26

1 Answers1

0

In Java, it would be because those properties are not public. How does Jython handle access to fields?

Terence Parr
  • 5,912
  • 26
  • 32
  • Those class variables are public. In Jython private variables are prepended with two leading underscores (example: __varname). Here's an expalanation: [link](http://www.ibm.com/developerworks/java/tutorials/j-jython2/section2.html#phidvar) – MD6380 Oct 11 '12 at 00:13
  • ah. I guess the debugger would tell us if you stop it in method Interpreter.getObjectProperty(). It will go into the object to try to get things out using reflection. I'm afraid I don't know jython at all so I'm not sure what the mismatch is. We can always add something into detect jython objects if you figure out what the convention is. thanks! – Terence Parr Oct 11 '12 at 18:59