views:

116

answers:

1
<py:match path="foo">
    <?python
        import os
        href = select('@href').render()
        SOMEWHERE = ...  # what file contained the foo tag?
        path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href)
        f = file(path,'r')
        # (do something interesting with f)
    ?>
</py:match>
...
<foo href="../path/relative/to/this/template/abcd.xyz"/>

What should go as "somewhere" above? I want that href attribute to be relative to the file with the foo tag in it, like href attributes on other tags.

Alternatively, what file contained the py:match block? This is less good because it may be in a different directory from the file with the foo tag.

Even less good: I could supply the path of the file I'm rendering as a context argument from outside Genshi, but that might be in a different directory from both of the above.

+1  A: 

You need to make sure that the driver program (i.e., the Python program that parses the input file) runs in the directory of the file containing the foo tag. Otherwise, you need to pass down the relative path (i.e., how to get from the directory in which the reader runs to the directory of the file being read) as a context argument to your Python code and add it to the os.path.join command.

With this setup (and using Genshi 0.6 installed on MacOS X 10.6.3 via the Fink package genshi-py26) the command os.getcwd() returns the current working directory of the file containing the foo tag.

For such complicated path constructs I also strongly recommend to use path=os.path.normpath(path), since you may not want such things to leak in your resulting HTML code.

user8472
Useful to some people I expect, but not quite what I was after: my code may run Genshi on file A, which has xi:include href="B/C/D", and D has xi:include href="../E", etc., what I really wanted to do is extract from Genshi the knowledge of the location of E or F... this would probably involve patching Genshi. Though as it happens I've switched to Rails since asking the question. :-)
Chris Boyle
Oh, I see. If the file with the `foo` tag was the main file then the above solution would indeed solve the problem (for some reason I have implicitly assumed this scenario, but it does indeed not follow from your question - sorry about that!). If this was yet another file included in the main file, the driver program couldn't know about its location and origin and could not include the correct path. In that case I have no solution of the problem (except having an explicit global constant at the beginning of *every* file that informs about its own location - certainly not feasible).
user8472
I am still using Genshi since I had already used Python for some time. Didn't bother to learn Ruby so far, but from all I have heard Rails might indeed be a good reason to start :^)
user8472