Using a global variable in Pweave template

236 Views Asked by At

Looking at the documentation for pweave here, it appears to be possible to access any data generated inside a template by the calling program, by setting the returnglobals variable.

Is it possible to do the opposite?, i.e. have the template reference a global variable in the calling script?

My use case is that I first pull some data from an SQL database, and then call pweave.pweave() using that data to populate the template. Currently I'm doing this by writing an intermediate file and then loading this in a preamble in the template. I would like to instead just pass this in as part of the global scope. I've tried declaring a variable global in the template, but this doesn't appear to work; I keep getting exception NameError.

1

There are 1 best solutions below

0
On

This can be done as follows:

In the calling script :

from pweave import Pweb
Pweb.globals = { "foo" : "bar" } # This creates a global var `foo` with value 'bar'
w = Pweb("inputfile.tex")        # Generate a Pweb class. We can't just call `pweave()`
w.weave()                        # Equivalent of `pweave()`

In the tex template:

The value of foo is <%=print(foo)%>

which will print "The value of foo is bar".

The reason for the weird dictionary is that the code uses the following call to evaluate your code:

exec compiled in Pweb.globals

You can get more information in the Python Documentation.