the f*ck rants about stuff

python

Latest posts related to :



  1. How to create your own markdown syntax with python-markdown

    Rationale

    Markdown (and I use Pelican with md) is not very good at handling images. I want an easy way in md for the image to fill the column but to link to the full size image automatically

    I want to turn:

    !![alt text](path/image.png title text)
    

    into:

    <a href="path/image.png"><img width=100% title="title text" alt="alt text" src="path/image.png"></a>
    
    Code
    aimg/__init__.py:
    
    #!/usr/bin/python
    # mardown extension. Wraps <a> tags around img and adds width=100%
    #
    # This makes easier to link to big images by making them fit the column
    # and linking to the big image
    #
    # run the module to check that it works :)
    
    from markdown.extensions import Extension
    from markdown.inlinepatterns import Pattern
    from markdown.util import etree
    
    class Aimg(Extension):
        def extendMarkdown(self, md, md_globals):
            md.inlinePatterns.add('aimg', AimgPattern('^!!\[(.+)\]\((\S+) (.+)\)$'), '_begin')
    
    
    class AimgPattern(Pattern):
        def handleMatch(self, m):
            a = etree.Element('a', {'href':m.group(3)})
            img = etree.Element('img', {
                'width': '100%',
                'src': m.group(3),
                'alt': m.group(2),
                'title': m.group(4)
            })
            a.append(img)
            return a
    
    if __name__ == '__main__':
        import markdown
        print(markdown.markdown('!![alt text](/images/image.png title text)', extensions=[Aimg()]))
    

    In your pelicanconf.py:

    import aimg
    MD_EXTENSIONS = ['codehilite(css_class=highlight)', 'extra', aimg.Aimg()]
    
    Bonus
    alternative solutions without an extension

    Yes, you can insert raw HTML in a markdown file

    <a href="path/image.png"><img width=100% title="title text" alt="alt text" src="path/image.png"></a>
    

    Yes, you can have them mixed. You cant add attributes tho

    [<img width=100% title="title text" alt="alt text" src="path/image.png">](path/image.png)
    

    Yes, with the extra extension you can have classes and modify them via CSS

    ![alt text](path/image.png title text){.classnamewith100%width}
    
    My version
    !![alt text](path/image.png title text)
    
¡ En Español !