I am using django.contrib.humanize intcomma tag to format large numbers like this $18,162,711,641
but what I want spaces instead of comma, like this $18 162 711 641
How can I achieve this? Thank you.
Thanks to Abdul Niyas P M
This is what works for me. I had to put this in app_name/templatetags directory and load it in template using {% load intspace %}
from django import template
register = template.Library()
#register.filter
def intspace(value):
import re
orig = str(value)
new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1> \g<2>", orig)
if orig == new:
return new
else:
return intspace(new)
inside template you can use it like
{{ 18162711641|intspace }}
Related
I want to pass an array of strings to Mako's render method but this doesn't work:
from mako.template import Template
mytemplate = Template(filename="some.template")
str = mytemplate.render(first="John", last="Smith", nicknames=[
"JJ", "Johnny", "Jon"])
print(str)
some.template =
Hello ${first} ${last}
Your nicknames are:
% for n in ${nicknames}:
${n}
% endfor
Within a '%' line, you're writing regular Python code that doesn't need the escaping:
% for n in nicknames:
${n}
% endfor
I have this code in my template file
{{markets|getSpiderItem:spider.id}}
Mysql has market_timezone and market_location and it connects to another table with spider_id so I filtered as follow:
#register.filter
def getSpiderItem(datas, spider_id):
return datas.filter(spider=spider_id)
I am getting this output:
<QuerySet [{'market_timezone': 'Turkey', 'market_location': 'Nigde'}]>
I want to print this QuerySet item on Django Template separately.
This function has already 2 for loop so I want to print just 1 time. I don't wanna use for loop like this:
{% for market in markets|getSpiderItem:spider.id %}
I want something like this but I couldn't figure out:
For Example:
{{markets|getSpiderItem:spider.id|market_timezone}} # I don't know the true way.
this is ok
{{markets|getSpiderItem:spider.id|market_timezone}}
modify getSpiderItem()
#register.filter
def getSpiderItem(datas, spider_id):
return iter(datas.filter(spider=spider_id))
define filter market_timezone():
#register.filter
def market_timezone(iitem):
return next(iitem).market_timezone
Expected content: Turkey
I'm using Python Pyramid with MongoDB. When I selected multiple images, it will save the image name into session. On the confirmation page, I will retrieve the image name from the session and thus get the image pathname from the database.
this is what I have right now in Views.py
session = request.session
greet_array = session['selectgreetings'].split(",")
greet = GreetingsImg(request)
print("session['selectgreetings']: " , greet_array)
for g in greet_array:
print('g: ' , g)
greetall = greet.get_by_name(g)
for ga in greetall:
greet_path = ga['path_name']
print('path: ', greet_path)
return {'greet_path':greet_path}
if I do this, it will print this results (Command Prompt)
session['selectgreetings']: ['Pics3', 'Pics2']
g: Pics3
path: static/image/greeting/03.jpg
g: Pics2
path: static/image/greeting/02.jpg
I was trying to combine the two paths so that I can get this in Command Prompt:
static/image/greeting/03.jpg, static/image/greeting/02.jpg
When I get the result above, I can use for loop in jinja2 to show the image selected:
{% for a in greet_path %}
<img src="/{{a}}" class="col-sm-5"/>
{% endfor %}
You can combine the contents of an array into a string, with each element separated by a comma, by doing this:
", ".join(greet_path)
Let's say I have an string variable called *magic_string* which value is set to "This product name is {{ product.name }}" and it's avaible at django template. Is it ever possible to parse that variable to show me "This product name is Samsung GT-8500" instead (assuming that name of the product is "GT-8500" and variable {{ product.name }} is avaible at the same template) ?
I was trying to do something like this, but it doesn't work (honestly ? Im not surprised):
{{ magic_string|safe }}
Any ideas/suggestions about my problem ?
Write custom template tag and render that variable as a template.
For example look at how "ssi" tag is written.
On the other hand, can you render this string in your view? Anyway here is an untested version of that tag:
#register.tag
def render_string(parser, token):
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError("...")
return RenderStringNode(bits[1])
class RenderStringNode(Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
var = context.get(self.varname, "")
return Template(var).render(context)
Perhaps I dont understand your question but what about,
from django.template import Context, Template
>>> t = Template("This product name is {{ product.name }}")
>>> c = Context({"product.name": " Samsung GT-8500"})
>>> t.render(c)
Regards.
In Jinja2, is it possible to have a Node from the AST render after all include statements have completed?
This is a key piece of a solution to a bigger puzzle.
Example code:
x.py
from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension
class XExtension(Extension):
tags = set(['x', 'get_x'])
def __init__(self, environment):
super(XExtension, self).__init__(environment)
environment.extend(
x = 0,
)
def parse(self, parser):
tag = parser.stream.next()
return getattr(self, "_%s" % str(tag))(parser, tag)
def _get_x(self, parser, tag):
""" Return the output """
return nodes.Const(self.environment.x)
def _x(self, parser, tag):
""" Add an x """
self.environment.x += 1
return nodes.Const('<!-- Adding an X -->')
env = Environment(
loader = FileSystemLoader('.'),
extensions = [XExtension],
)
template = env.get_template('x.html')
print template.render()
x.html
Xx {% x %} Xx {% x %}
{% include "y.html" %}
Xs xes: {% get_x %}
y.html
Yx {% x %}
Ys xes: {% get_x %}
The output is
Xx <!-- Adding an X --> Xx <!-- Adding an X -->
Yx <!-- Adding an X -->
Ys xes:3
Xs xes 2
How may it be possible to have Xs xes count the X's in y.html, which is the behaviour I desire and expect?
In other words, is there a way to delay the parsing or flattening to text returned from the _get_x() in x.html?
Thank you very much for reading.
Kind regards,
Brian
Jinja2 does streaming of template data. The template is evaluated instruction for instruction into a stream of smaller strings that gets concatenated into an actual unicode string by the render() method. However you can also get hold of the stream by calling into generate() instead of render().
With some in-band signalling and postprocessing of the stream one might probably be able to implement something like that, but it's against the way of how Jinja2 was designed so it might break horribly and is totally unsupported.