…is my new best friend.
At least where simple layouts are concerned, forget table markup, or even CSS table markup.
…is my new best friend.
At least where simple layouts are concerned, forget table markup, or even CSS table markup.
Emacs can also be annoying when it autoinserts text without checking to see if it’s already there. Case in point, gettext .po files under Emacs 23.1. For whatever reason, my copy kept inserting this header whenever I opened a translation file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR Free Software Foundation, Inc.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSIONn"
"PO-Revision-Date: 2012-12-10 05:06+0000n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>n"
"Language-Team: LANGUAGE <LL@li.org>n"
"MIME-Version: 1.0n"
"Content-Type: text/plain; charset=CHARSETn"
"Content-Transfer-Encoding: 8bitn"
|
If this header sneaks into a .po file, when you try to compile the file with Django’s compilemessages command, you get the following error:
1
2
3
4
5
6
7
|
$ django-admin.py compilemessages
processing file django.po in /home/user/project/app/locale/de/LC_MESSAGES
/home/user/project/app/locale/de/LC_MESSAGES/django.po: warning: Charset "CHARSET" is not a portable encoding name.
Message conversion to user's charset might not work.
/home/user/project/app/locale/de/LC_MESSAGES/django.po:21: duplicate message definition...
/home/user/project/app/locale/de/LC_MESSAGES/django.po:7: ...this is the location of the first definition
msgfmt: found 1 fatal error
|
What seems to happen is that this header is only inserted when you use C-x C-f to open a file. When opening a file directly from the command line, this corruption does not seem to occur.
If you look at the PO Group configuration options, this text is listed there as the default PO file header. I haven’t validated this as a solution, but you should be able to switch this value to be the comment character “#”, and that should take care of the problem.
Also, why the hell does the PO major mode not allow you to destroy entire msgid’s and their translations? This is really annoying. Yes, it’s nice sometimes when programs limit your options, but in this case, Emacs was messing up by inserting the bad header, then refusing me the option of removing it.
Update: I’ve posted the code at github here.
Wanting to keep my server-side and client-side templates identical, I noticed there wasn’t a good solution for using Mustache/Pystache/Handlebars templates alongside the Django templating language.
The existing one that I saw used Pystache internals, and I’m not even sure they’re still valid in the latest Pystache versions.
The other existing one that I saw let you do the equivalent of #include “something.mustache” within the Django templates, which wasn’t what I was looking for either.
So I went ahead and wrote a set of PystacheTemplate and Pystache*Loader classes which do it all within the specifications of the Django infrastructure, and, I set them up so that you can specify the exact file extensions you want them to operate on, i.e. just .mustache, .handlebars, and .hbs files by default. This doesn’t mean you can mix Mustache directly into Django templates, which doesn’t make sense (and is mildly redundant), but it does mean you can render complete Mustache template files directly, which is awesome if you’re wanting to share those templates or partials between client and server.
Copy this file somewhere into your project or app folders:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
"""
Copyright (c) 2012 Max Vilimpoc
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
"""
from django.template.loaders import app_directories, filesystem
from django.template.base import TemplateDoesNotExist
import pystache
import os
"""
Based on:
https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.Template
https://docs.djangoproject.com/en/dev/ref/templates/api/#loading-templates
https://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language
"""
class PystacheTemplate():
def __init__(self, templateString):
self.parsed = pystache.parse(templateString)
self.renderer = pystache.Renderer()
def render(self, context):
# Flatten the Django Context into a single dictionary.
flatContext = {}
for d in context.dicts:
flatContext.update(d)
return self.renderer.render(self.parsed, flatContext)
"""
Based on:
https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
Yeah, it's two identical classes separated by a name.
Metaprogramming comes to mind.
According to django.template.loader.BaseLoader:
"A loader may return an already-compiled template instead of the actual
template source. In that case the path returned should be None, since the
path information is associated with the template during the compilation,
which has already been done."
---
We can make the Loader check the file extension as well,
so it will only parse Mustache-compatible files:
.handlebars, .hbs, .mustache, and so on.
This means you can actually keep using the normal Django loaders
too, for other file extensions!
---
The key piece is in django/template/loader.py
def find_template(name, dirs=None):
[...]
for loader in template_source_loaders:
try:
source, display_name = loader(name, dirs)
return (source, make_origin(display_name, loader, name, dirs))
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(name)
[...]
Note:
This could still mess up if the custom loader passes
through a Handlebars template with an .html extension.
Later loaders would then throw a fit.
"""
EXTENSIONS = ['.handlebars', '.hbs', '.mustache']
class PystacheAppDirectoriesLoader(app_directories.Loader):
is_usable = True
def load_template(self, template_name, template_dirs=None):
# Only allow certain template types.
filename, extension = os.path.splitext(template_name)
if extension not in EXTENSIONS:
raise TemplateDoesNotExist
source, origin = self.load_template_source(template_name, template_dirs)
template = PystacheTemplate(source)
return template, None
class PystacheFilesystemLoader(filesystem.Loader):
is_usable = True
def load_template(self, template_name, template_dirs=None):
# Only allow certain template types.
filename, extension = os.path.splitext(template_name)
if extension not in EXTENSIONS:
raise TemplateDoesNotExist
source, origin = self.load_template_source(template_name, template_dirs)
template = PystacheTemplate(source)
return template, None
"""
Now update the settings.py file to use the custom Loaders,
putting them ahead of Django's default Loaders in the
TEMPLATE_LOADERS setting.
TEMPLATE_LOADERS = (
'project.templates.PystacheFilesystemLoader',
'project.templates.PystacheAppDirectoriesLoader',
[...]
)
"""
|
Then you can just update the settings.py file to use the custom Loaders, putting them ahead of Django’s default Loaders in the TEMPLATE_LOADERS setting:
1
2
3
4
5
|
TEMPLATE_LOADERS = (
'project.templates.PystacheFilesystemLoader',
'project.templates.PystacheAppDirectoriesLoader',
[...]
)
|
Then if you have, say, a file called index.handlebars somewhere in one of your app directory template/ folders or somewhere else in the TEMPLATE_DIRS list, you can just do this in one of your views:
1
2
|
def someView(request):
return render_to_response('index.handlebars', { 'title': 'Hello, Awesome.' })
|
And all will be good.
Please let me know in the comments if you have any problems with this. (Speed might one of them, I haven’t extensively tested this yet. But I plan to cache these using the Django template cache loader.)
Google falls over again looking for:
“generating list of mustache tags in a template”
“regular expression list of mustache tags in a template”
“grep list of mustache tags in a template”
“get list of mustache tags in a template”
“grep expression for mustache tags”
What am I trying to do? I have a Mustache template, and I want to pull out the list of tags I am using in it, because I need to filter a bigger chunk of JSON data to only contain those tags. This JSON data will eventually be used as the context that is then used to .render() the output.
Google needs to reinstate exact-quote indexing, the fuzzy searches of the past few years are making it really hard to find relevant links. (Yes, I probably should have the regex rules memorized, but this can’t be the first time someone’s been looking for this.)
For the record, the command I used to generate this list:
1 |
grep -o -E "{{(w+)}}" file.mustache | sort --unique
|
Update 2 March 2013:
The above command was perhaps a bit too simple, it gives the tags in the form of a list of “{{tag}}”.
To get rid of the mustache brackets, you have to run the point through sed.
1 |
grep -o -E -e "{{(w+)}}" index.handlebars | sort --unique | sed -e 's_{{__g' -e 's_}}__g'
|
In Python, the following regex will also give you all the tag names, sans brackets:
1
2
|
import re
sorted(set(re.findall('{{[^/#]*(w+)}}', template_text)))
|
As a learning exercise, I converted a piece of Javascript code i’d written into CoffeeScript.
So what’s wrong with this?
1
2
3
4
5
6
7
8
9
|
initialize = ->
$('select[name="language"]').change (e) ->
renderLocalizedText $(@).val()
return
# Initialize the application on DOM ready event.
$(document).on 'ready', ->
console.log "hello, world"
initialize
|
Oh that’s right, initialize doesn’t get called.
It must be “initialize()” when you want to call a function w/no params. But when you do have params, you can leave the parens off. What inconsistent bullshit is this? I guess it’s nice that “initialize” by itself is a statement w/o a side effect. But then when you run it through the compiler (when the hanging return isn’t there), it spits out “return initialize;”, which isn’t what I meant at all and could be a side effect for anyone trying to maintain this down the road. Better to make it explicit that this thing won’t return anything a caller can (ab)use, until and unless I choose to make that the case.
So I’ve been adding hanging returns so the compiled code returns nothing as often as it should.
Sigh, I don’t know that I dig the whole implicit “return whatever was on the last line” thing that so many of these terse scripting languages have. And it strikes me as a weird idea to try and save on parens.
So the CoffeeScript adventure begins, but I’ll be damned if I’m not already building the defensive programming idioms in.