View Single Post
Old 10-10-2013, 06:05 PM   #8
chaley
Grand Sorcerer
chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.
 
Posts: 12,522
Karma: 8065528
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
Quote:
Originally Posted by kcz View Post
I have created a user defined template function called format_index with 1 argument. Here is the code:

Code:
def evaluate(self, formatter, kwargs, mi, locals, val):
    return re.sub('\.00', '', format_number(field(val), '[[0:05.2f]]'), flags=re.I)
The template in the custom column looks like this:

{series_index:format_index()}

Unfortunately I get the following error:

TEMPLATE ERROR global name 're' is not defined

Any idea what the problem is?
You are conflating the template language and python, and also not importing the necessary python modules. When writing user defined functions you must use python and only python.

One version of your function in python is
Code:
def evaluate(self, formatter, kwargs, mi, locals, val):
	import math
	# Check if the argument is empty. If so, return the empty string
	if val == '':
		return ''
	# Not empty. Must be a number. If it isn't, bad things will happen.
	v = float(val)
	# If it is an integer, return an 2-digit string zero padded
	if math.floor(v) == v:
		return '{:02.0f}'.format(v)
	# Not an integer. Return a 2.2 digit string.
	return '{:05.2f}'.format(v)
chaley is offline   Reply With Quote