Help pages using Markdown view renderer

4 followers

This wiki article has not been tagged with a corresponding Yii version yet.
Help us improve the wiki by updating the version information.

This tutorial describes how to write your views for help pages using Markdown syntax to be able to generate PDFs from same source files.

View renderer

Create the file components/MdViewRenderer.php with following contents:

<?php
class MdViewRenderer extends CViewRenderer
{
    public $fileExtension='.md';
 
    protected function generateViewFile($sourceFile,$viewFile) {
        $md=new CMarkdown;
        $input = file_get_contents($sourceFile);
        $output = $md->transform($input);
        file_put_contents($viewFile,$output);
    }
 
}

Add it to the application config in config/main.php:

'components' => array(
        'viewRenderer' => array(
            'class'=>'MdViewRenderer',
        ),
        // .... other components config
    ),

Help pages

Create some help pages in the views/site/help directory as files with the .md extension. Your favourite text editor should enable syntax higlight in them.

Add a view action in your SiteController:

public function actions()
    {
        return array(
            'help'=>array(
                'class'=>'CViewAction',
                'basePath'=>'help',
            ),
            // .... other actions
        );
    }

Now just link the pages in your main menu:

'url' => array('/site/help', 'view'=>'sales'),

Generating PDF

Markdown files can be converted to PDF using pandoc, a swiss-army knife written in Haskell for converting documents between various formats. It calls Latex internally, so it must also be available on your system.

Assuming all images in the .md files start with /images we need to add a proper relative path for pandoc to find those files. So let's prepend ../../.. to them using sed:

TMPDIR=/tmp
for m in `ls *.md`; do
   sed 's/^!\[\(.*\)\](\(.*\))$/![\1](..\/..\/..\/..\2)/g' $m > ${TMPDIR}/$m;
done

Modified files are put into a temporary directory to avoid breaking them for HTML.

Generate a PDF using pandoc:

TMPDIR=/tmp
pandoc -S -N -Vlang=polish --latex-engine=xelatex ${TMPDIR}/*.md -o test.pdf

Instead of using a wildcard (*) specify all files manually to force order in which pandoc concatenates them.

Total 2 comments

#14413 report it
nineinchnick at 2013/08/09 07:02am
Interesting post

It turned out to be so simple that I had to share it :-) It's a nice example of using view renderers and keeping views with Markdown clean of any other syntax.

#14410 report it
trond at 2013/08/09 06:30am
Interesting post

Thanks for sharing. A little information about pandoc would be a nice addition to the article. I had to look that up.

Leave a comment

Please to leave your comment.

Write new article