Spyce packs a few more features when it comes to embedding code. An interesting feature worth looking at is active tags, which are tags that basically take the place of Python code or other text, passing the code part off to a module. This can cut development time and reduce clutter in Spyce files, among other things. In my opinion, active tags are best understood if you skip the prose details and jump right into an example. First, let's define a few tags in color.spi: [[.tagcollection]] [[.begin name=red buffers=True]] [[.begin name=green buffers=True]] [[.begin name=blue buffers=True]] Before we continue, notice that most of the above Spyce commands come in a “[[.X]]” structure. These are called Spyce directives, and they are used to communicate with Spyce. Here, we use it to declare the file to be a tag collection and then to describe individual tags. Let's now put the above tags to use in colortest.spy: [[.taglib from=color.spi as=color]] When you run colortest.spy, active tags should start to make sense. In color.spi, we defined three tags, red, green and blue. Notice how we set buffers to True. This allows us to access the content inside the tags with _content. In colortest.spy, _content is “Red”, “Green” and then “Blue”. Active tags can also access attributes. Say, for example, that we want to define a tag that allows a custom color to be set through an attribute. We could add this definition on to color.spi: [[.begin name=cust buffers=True]] Here's the new tag in action: [[.taglib from=color.spi as=color]] There are some situations where a tag will not come in pairs. For example, let's say we wanted to add an information tag to color.spi. This is how it would be done: [[.begin name=information singleton=True]] It's also possible to create active tags from Python classes. Using this method, we can duplicate color.spi as color.py: import spyceTag def genColorTag(color): class color(spyceTag.spyceTagPlus): name = color def syntax(self): return color red = genColorTag('red') class cust(spyceTag.spyceTagPlus): name = 'cust' def syntax(self): class information(spyceTag.spyceTagPlus): name = 'information' def syntax(self): class color(spyceTag.spyceTagLibrary): Creating a tag library in Python can take more effort, but it's pretty straight-forward. We start off by generating the classes red, blue and green from the genColorTag function. The classes are subclasses of spyceTag.spyceTagPlus. Notice how we use the syntaxPairOnly method to indicate that the tag should come in a pair. Next, we create the cust tag. In the first three classes, we split the HTML generation between begin, body and end, but in cust, we do it all in body. There's no reason why everything just can't go in body to begin with, but I want to acknowledge the other two methods. Then, we create the information class, making sure to call syntaxSingleOnly. Finally, we create a color class and list all our tags in it.
blog comments powered by Disqus |
|
|
|
|
|
|
|