How to pass html directly to template - python

I want to pass HTML directly as a parameter in template().
I know I could do something like:
%for i in array:
<a>{{i}}</a>
%end
but I need to pass it directly when I call template,
I tried replacing &lt and &gt with < > with javascript but that did not work.
I want to do this:
{{results_of_i_in_array}}
and the loop will occur in my main rather than in the template,
I never found anyone asking the same question.
Note: this question is NOT a duplicate of this question.
I am using bottle default templating system, thanks in advance.

Bottle doc:
You can start the expression with an exclamation mark to disable
escaping
for that expression:
>>> template('Hello {{name}}!', name='<b>World</b>')
u'Hello <b>World</b>!'
>>> template('Hello {{!name}}!', name='<b>World</b>')
u'Hello <b>World</b>!'

Related

How to break line on html when use string from python

Basically I'm building a chatbot using python. When running on python, I can display the answer with multiple lines by using \n tag. However , when I bring it to HTML to display it on website using Flask, it cannot render \n tag so there is no line break.
I have also tried to replace \n to <br/> but no help. It prints out the br tag instead of converting it to a line break.
Please guide.
in some textArea <br/> will not word
you can use
to brekline
just like use to stand for space in html
You could try to pass <br> It's the escaped <br> Tag Link
Try using these options.
If your content-type is html, then use
"String to be displayed"+"<br \>"+"The string to be displayed in new line"
Else, If your content-type is plain text then use
"String to be displayed"+"\n"+"The string to be displayed in new line"
I had the same problem. Despite i used Django for my website i suppose the logic and syntax are the same.
You can do it through the variable and adding "|safe" in your html code.
For example, in your python code you have:
broken_string = "first line<br>second line"
and
return render_template('index.html', html_broken_string = broken_string)
And in your HTML code you should have:
{{ html_broken_string|safe }}
That should do the work.
P.S: I don't remember if you can actually pass string directly in your render_tamplate() function and omit creation of a new variable in Flask, so i didn't write that. But you can try.

In python the Jinja2 template returns a backslash in front of a double quote, I need to remove that

One of the lines in my jinja2 template needs to return
STACKNAME=\"",{"Ref":"AWS::StackName"},"\"
Putting the above into the template returns
STACKNAME=\\\"\",{\"Ref\":\"AWS::StackName\"},\"\\\"
I tried creating a variable
DQ = '"'
and setting the template as
STACKNAME="{{DQ}},{{{DQ}}Ref{{DQ}}:{{DQ}}AWS::StackName{{DQ}}},{{DQ}}"
but the result still puts a backslash in front of the {{DQ}} variable
I also tried putting in a unique string %%%DQ%%% and then getting the results and then doing a string replace but it still gives me the backslash.
How do I get the results I want?
UPDATE:
My apologies. It turns out that it is not the jinja2 template that is returning the escaped quotes. I am making a later call in the script to:
lc.UserData=Base64(Join("", [commandList]))
And it is this call to the Troposphere Module for Base64 and/or Join that is causing the problem and inserting the escapes.
Testing Further shows specifically that it is Base64 that does the escaping.
This feels like a hack and I hope someone has a better solution but I solved the problem by doing the following.
In the template, I made the line look like this:
STACKNAME="QQ,{QQRefQQ:QQAWS::StackNameQQ},QQ"
Then, in the last line of the program where I currently have:
print t.to_json()
I changed it to
print t.to_json().replace("QQ", '"')
Which produces exactly what I'm looking for.

Django/Textile/Pygments: " ' > being escaped

I have a blog written in django that I am attempting to add syntax highlighting to. The posts are written and stored in the database as textile markup. Here is how they are supposed to be rendered via template engine:
{{ body|textile|pygmentize|safe }}
It renders all the HTML correctly and the code gets highlighted, but some characters within the code blocks are being escaped. Specifically double quotes, single quotes, and greater than signs.
Here is the Pygments filter I am using: http://djangosnippets.org/snippets/416/
I'm not sure which filter is actually putting the escaped characters in there or how to make it stop that. Any suggestions?
shameless plug to me answering this on another page:
https://stackoverflow.com/a/10138569/1224926
the problem is beautifulsoup (rightly) assumes code is unsafe. but if you parse it into a tree, and pass that in, it works. So your line:
code.replaceWith(highlight(code.string, lexer, HtmlFormatter()))
should become:
code.replaceWith(BeautifulSoup(highlight(code.string, lexer, HtmlFormatter())))
and you get what you would expect.

Converting \n to <br> in mako files

I'm using python with pylons
I want to display the saved data from a textarea in a mako file with new lines formatted correctly for display
Is this the best way of doing it?
> ${c.info['about_me'].replace("\n", "<br />") | n}
The problem with your solution is that you bypass the string escaping, which can lead to security issues. Here is my solution :
<%! import markupsafe %>
${text.replace('\n', markupsafe.Markup('<br />'))}
or, if you want to use it more than once :
<%!
import markupsafe
def br(text):
return text.replace('\n', markupsafe.Markup('<br />'))
%>
${text | br }
This solution uses markupsafe, which is used by mako to mark safe strings and know which to escape. We only mark <br/> as being safe, not the rest of the string, so it will be escaped if needed.
It seems to me that is perfectly suitable.
Be aware that replace() returns a copy of the original string and does not modify it in place. So since this replacement is only for display purposes it should work just fine.
Here is a little visual example:
>>> s = """This is my paragraph.
...
... I like paragraphs.
... """
>>> print s.replace('\n', '<br />')
This is my paragraph.<br /><br />I like paragraphs.<br />
>>> print s
This is my paragraph.
I like paragraphs.
The original string remains unchanged. So... Is this the best way of doing it?
Ask yourself: Does it work? Did it get the job done quickly without resorting to horrible hacks? Then yes, it is the best way.
Beware as line breaks in <textarea>s should get submitted as \r\n according to http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4
To be safe, try s.replace('\r\n', '<br />') then s.replace('\n', '<br />').
This seems dangerous to me because it prints the whole string without escaping, which would allow arbitrary tags to be rendered. Make sure you cleanse the user's input with lxml or similar before printing. Beware that lxml will wrap in an HTML tag, it just can't handle things that aren't like that, so get ready to remove that manually or adjust your CSS to accommodate.
try this it will work:-
${c.info['about_me'] | n}
There is also a simply help function that can be called which will format and santize text correctly replacing \n for tags (see http://sluggo.scrapping.cc/python/WebHelpers/modules/html/converters.html).
In helpers.py add the following:
from webhelpers.html.converters import textilize
Then in your mako file simply say
h.textilize( c.info['about_me'], santize=True)
The santize=True just means that it will make sure any other nasty codes are escaped so users can't hack your site, as the default is False. Alternatively I make do a simple wrapper function in helpers so that santize=True is always defaults to True i.e.
from webhelpers.html.converters import textilize as unsafe_textilize
def textilize( value, santize=True):
return unsafe_textilize( value, santize )
This way you can just call h.textilize( c.info['about_me'] ) from your mako file, which if you work with lots of designers stops them from going crazy.

python/genshi newline to html <p> paragraphs

I'm trying to output the content of a comment with genshi, but I can't figure out how to transform the newlines into HTML paragraphs.
Here's a test case of what it should look like:
input: 'foo\n\n\n\n\nbar\nbaz'
output: <p>foo</p><p>bar</p><p>baz</p>
I've looked everywhere for this function. I couldn't find it in genshi or in python's std lib. I'm using TG 1.0.
def tohtml(manylinesstr):
return ''.join("<p>%s</p>" % line
for line in manylinesstr.splitlines()
if line)
So for example,
print repr(tohtml('foo\n\n\n\n\nbar\nbaz'))
emits:
'<p>foo</p><p>bar</p><p>baz</p>'
as required.
There may be a built-in function in Genshi, but if not, this will do it for you:
output = ''.join([("<p>%s</p>" % l) for l in input.split('\n')])
I know you said TG1 my solution is TG2 but can be backported or simply depend on webhelpers but IMO all other implementations are flawed.
Take a look at the converters module both nl2br and format_paragraphs.

Categories

Resources