Blog Entry 10 years, 3 months ago

Django, Vim and snippets

My experience on leveraging shortcuts or snippets in developing with Django projects, especially when coding in Vim.

Shortcuts/snippets are very useful and fun. It could be leveraged in all editing environments, coding included. It would help:

  • Reduce time of making tedious key presses, especially when you have to make it multiple time
  • Reduce risk of typos.
  • ...

So, how do we using snippet shortcuts when developing with Django, especially in Vim?

My favourite choice is SnipMate.

  • Installation is simple, just unzip and put everything into your ~/.vim, or bundle of Pathogen.
  • Usage: Type the short text then TAB to get the full snippet. For example, with for<TAB>, you will get:
for needle in haystack:
    # code...
  • Another good thing is you could use further TABs to jump and edit content of the variables/placeholders (in above code, those are needle, haystack and # code...)
  • Other usable snippets are: if, def, cl(ass),...

While the Python part is almost enough to me (only added some for inserting debug,...) the HTML template is not good enough. You don't have anything like {% for needle in haystack %}...{% else %}...{% endfor %} or all Django-specific template directions.

  • Solution: Add you custom snippets into ~/.vim/../snipmate/snippets.htmldjango.snippets. Example: 
snippet {
    {% ${1} %}
snippet for
    {% for ${1} in ${2} %}
      ${3}
    {% else %}
      ${4}
    {% endfor %}
...
  • Notice: While the Vim's detect of Django HTML file is not really good (check this: https://gist.github.com/fabiomcosta/2956964) you could make symlink from djangohtml to html to be able to use your custom snippets in all project templates.

After all modifications made to the snippet files, you should restart Vim in order to have those changes taking effect.

Recent Reads