Hooked on Myghty

I’ve been programming web sites for many years, and have yet to come across a templating language as appealing as Mason / Myghty. To avoid confusion I’m going to talk about Myghty, but since its a direct port of Mason (plus some MVC stuff) all of my comments apply to Mason as well (unless otherwise noted). So if you find yourself stuck using Perl (or you prefer Perl) and something here sounds appealing, by all means use Mason as I did.

Despite Myghty only having come into existence approximately 14 months ago, the code-base is stable, very quick, and has been running in production environments for over 8 months. This is mainly because it started as a very direct port of Mason to Python, it then grew a few additional features that made it great for MVC use. The methodologies present in Mason (thus Myghty as well) are known to scale to very large and complex sites, as this list of Mason-powered sites shows. But it’s the little things added up that really make Myghty my template language of choice.

This is a rather lengthy post as I highlight and explain some core concepts of Myghty, please bear with me… also, if you’d like to follow along and try the examples out, its really easy to get started using Myghty with Paste.

Syntax

Template languages vary a lot in style, there are the very basic string replacement template languages all the way to more advanced template languages. Myghty definitely weighs in on the latter as it has many of its own concepts with regards to templating that produce a very robust and advanced templating system.

The syntax itself is also very appealing to me, as I’m a fan of templating languages that keep their guts inside < > signs. The only exception to this being if you need a quick line of Python, which is done just by having a % in front of it. Here’s what a loop would look like:


% for person in people:
   <b>Hi</b><% person %>
% #end

You’ll notice an additional line is needed to indicate the end of the loop. This is because Python uses white-space to determine blocks and Myghty needs to know when the indentation is over.

Components and Inheritance

In Myghty, each template is more properly referred to as a Component. When a component is directly called as a request (or sub-request), inheritance is applied. This is how a site’s skin is typically applied. Rather than having to specify in your template that it includes or extends some other template, in Myghty your component automatically inherits from an autohandler file above it.

An easier way to think of it is to consider your template directory layout as a Class, and all the templates in it are methods. Every directory inside that root one is another Class, and so on. The autohandler in this context acts much like your __init__ method. Here’s a little example:


	
  1. /autohandler



Sitename


% m.call_next()

  1. /index.myt

Welcome to your site!


When the autohandler encounters a m.call_next() command it calls the next component in the inheritance chain until eventually it gets down to the original component that was requested. It could end up going through several autohandler files on the way down to your component, each one creating sections of your site appropriate for where the component is located.

This makes life really easy if you need to move content around and have it pick up the proper “skin” for the site. The concept is also rather easy for web designers to grasp, and I’ve had no problem teaching web designers the basics they need to know about Myghty to be quickly adding sections to a website.

Methods

Of course, we have to have a way for our index.myt page to get its own title up to the autohandler which creates that section. This is where Methods become useful. Methods allow you to define (typically small) sections inside your component that can be called almost like functions, even from outside the component the method is in. If you’ve ever had to write a Python function for use in a template that has so much HTML in it you went nuts, methods will make you quite happy (more on that shortly).

Here’s our above example with the /index.myt page filling in the HTML title:


	
  1. /autohandler



% m.call_next()


Your Site
%method>

  1. /index.myt

Welcome to your site!


– Welcome Page
%method>

The title this page will have is Your Site - Welcome Page. When calling a method, we use the same syntax as when calling another component (yes, an entire component can be called). The <&&> syntax is used, with a method we also declare the name of it following the :. Using the SELF location tells Myghty to search down the inheritance (including itself), so calling SELF:title searches down the inheritance until it comes across the most deeply nested component containing a method called title. Using PARENT searches the up looking for the first component that contains a method called title.

This way we can have our new components mix content from up the inheritance chain. They can even mix content anywhere in between, take this more complex example where we use the inheritance chain with methods and lookups to put together the proper title for a fictitious product page:


	
  1. /autohandler is the same as above
  1. /products/autohandler

% m.call_next()


– Products
%method>

  1. /products/sprocket.myt

Buy a sprocket, they’re great….


– Sprocket Details
%method>

The title will now be Your Site - Products - Sprocket Details if you request the /products/sprocket.myt component. As I mentioned earlier, this makes it very easy to move files around as inheritance fills in so much for you.

Component Calls and Arguments

While I’m just using these methods calls for the title, the contents of a method block can contain Python code and variables as well just as our component can. In keeping with the spirit of explanation by example, here’s how we could put a sidebar in our main autohandler:


	
  1. /autohandler







% m.call_next()

  1. /sidebar.myt


If you’ve used Rails, they call the ability to insert other components “rendering a partial”. If you’re other component needs some data that you have in your autohandler, here’s how you can pass variables into a component when you call it:


	
  1. /autohandler







% m.call_next()

  1. /sidebar.myt



argument = “Default”
%args>

The args block designates arguments that can be passed into the component, as well as letting you setup default arguments in case none were passed in.

Init and Python Blocks

As much as we all hate it (in a MVC context), sooner or later you need to have a chunk or two of Python code in your template. In Myghty we have several options for putting Python in our component, the most obvious is to use the % code... syntax but that quickly becomes tiresome if we have 8 lines of Python code. So we can put that in a block like so:


	
  1. /somefile.myt


x = 10
y = 20
z = []
for a in range(1,100): z.append(x*y+a)
%python>

Having python blocks like that is a very common scheme in many Python template languages, but has a side-effect that can become quite irritating. It sticks you with having code through-out your template or having a large block at the top. In Myghty, there’s another block that can be defined only once in a component called an init block. It looks exactly like the above example but instead of <%python> we use <%init>.

This init block can go anywhere in your component, and I usually stick it at the very bottom. This way when designers open the page they aren’t smacked with Python code and they can just ignore the foreign language at the bottom. The init block runs before the rest of your component, so you can stick in variable initialization, import a module if you need one, etc. I’ve found this to be a great way to keep the Python bits that creep into my components out of the way.

Caching

If the rest wasn’t enough to interest you, this section and the next really start to lay on the goods. Myghty lets any component cache itself, you can cache by key as well in case there’s several different versions of a component that you wish to use. Caching a component is very useful and its very easy in Myghty.


	
  1. /index.myt

Welcome to your site!


– Welcome Page
%method>


if m.cache_self(): return

do_really_slow_stuff()
%init>

Upon the component load, it will check to see if it has a cached version of itself on hand (and cache itself in the process otherwise), then return the output. You can cache individual parts of a component, and even cache function output (if its pickle-able). This ability makes it very easy to design a site, then go through and if sections of it take a long time, put a cache command in the parts of the page that render the slowest.

The caching system can use the file system, memory, or memcached to store data.

Multiple Component Roots

In Myghty, the directory that is searched for components is called the Component Root. An extremely powerful and more advanced function is to use multiple component roots.

Here’s what a standard configuration for Myghty would look like to define a component_root to search:


component_root = "/path/to/your/components"

Most (if not all) template languages let you specify the directory containing your templates. Myghty goes another step furthor and lets you define multiple roots:


component_root = [
{'main':"/web/sites/mysite/htdocs"},
{'components':"/web/sites/mysite/components"},
{'alt':"/usr/local/lib/special-comp"}
    ]

If you have multiple component roots, and you ask for /lib/view_user.myt, Myghty will search for that under each of those directories you specified to component_root.

This is a very powerful ability as you can add component roots and override other components. I cannot stress enough how useful and vital this feature is for me. It’s exceptionally useful if you want to run multiple sites with different skins, ie, co-branding your site perhaps. All you need to do is setup a new Myghty server, and configure the component roots to the other site and make a new component root for your co-branded site.

Here’s a possible config given our original site is configured as shown above:


component_root = [
{'cobrand':"/web/sites/cobrand/htdocs"},
{'main':"/web/sites/mysite/htdocs"},
{'components':"/web/sites/mysite/components"},
{'alt':"/usr/local/lib/special-comp"}
    ]

Now I could just create a /autohandler in the new directory, and when Myghty is searching the inheritance chain looking for autohandler’s, it loads /web/sites/cobrand/htdocs/autohandler instead of /web/sites/mysite/htdocs/autohandler. I could also specify a certain component using the key in front, main:/some/component.myt.

Using Myghty in MVC

Myghty has Sessions, Filters, Content Escaping, and some rather advanced functionality for switching buffer spaces on component output that even surpasses Mason. A further extension of the Component concept is the Module Component concept, which allows you to design your web application in the MVC paradigm with a Controller class.

The benefit of using Myghty’s MVC vs using Myghty strictly as a template language within a different MVC web application, is that you gain the ability to easily call Controllers from within a template. While you might wonder at first why you’d want to do this, it can be very useful when using AJAX and a section of a page is going to be filled in by an AJAX request. Calling the Controller for its output from the template lets you easily put in the starting content. There’s other benefits as well, my prior article on Myghty covered the other import reason, which is the Custom Resolvers ability that you wouldn’t have if a different framework is handling the request.

If this has you interested and you’d like to learn Myghty in depth, my suggestion would be to read the Mason Book while keeping the Myghty docs handy to see what the Python implementation looks like. Myghty is a very advanced template framework that handles the VC in MVC, and I’ve yet to find another template language I enjoy as much.