My friends and family are under attack in Ukraine.
Donate to protect them directly or help international organizations.

Integrating Markdown with Symfony

April 25th, 2011

Context

I needed to create a number of static help pages in three languages in a Symfony 1.4 application. Using the XLIFF translation files seemed absurd, since I knew that I will include a lot of HTML. As you know, XLIFF translation files are XML, and so any HTML needs to be converted to entities, which makes maintenance a pain. Also, loading the entire manual's XLIFF when requesting a single page is not optimal. And so, I decided to create partials using the following structure: _docs/{lang}/{title}.php. This method would organize my pages nicely and will only load what is needed.

Then, I remembered that we were planning to hire a technical writer for the rest of the manual. I wanted to make his life as easy as possible and the source files easy to read for everyone. I went that far; I might as well write the manual using Markdown. Because Symfony can cache static pages, Markdown will only parse each page once. I did not have to worry about performance! Here is how to quickly add Markdown to your Symfony 1.4 application.

Solution

  1. Download the paser
  2. Copy the PHP file to your lib/helper or apps/{application}/lib/helper directory
  3. Rename the file to MarkdownHelper.php
  4. In your controller, load the Partial helper: $this->getContext()->getConfiguration()->loadHelpers(array(‘Partial'));
  5. Load your partial: $this->content = get_partial(‘{module}/{partial}');
  6. In your template, load the Markdown helper: <?php use_helper(‘Markdown'); ?>
  7. Parse and output: <?php echo Markdown($content); ?>

Notes

Steps 4 and 5 can also be achieved on the template level as well.

The reason for calling the Markdown helper in the template and not in the action is due to Symfony's output escaper (and also because presentation logic belongs in the View). By default, Symfony converts all HTML tags to entities, which is great for security, in case the input comes from an untrusted source. Had we parsed with Markdown at the controller level, you would have seen HTML tags in your browser. If, for any reason, you still wish to parse at the controller level, make sure to output using this code: $sf_data->getRaw(‘content');

Here is a link to short and comprehensive Markdown Syntax Documentation.

Previous: Symfony – subfolders for partials Next: What OpenStreetMap is and what it’s not