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.
Related
I'm new to Django and am trying to use unittest to check if there's some text in an outbound email:
class test_send_daily_email(TestCase):
def test_success(self):
self.assertIn(mail.outbox[0].body, "My email's contents")
However, I'm having an issue with mail.outbox[0].body. It will output \nMy email's contents\n and won't match the test text.
I've attempted a few different fixes with no luck:
str(mail.outbox[0].body).rstrip() - returns an idential string
str(mail.outbox[0].body).decode('utf-8') - no attribute decode
Apologies, I know this must be a trivial task. In Rails I would use something like Nokogiri to parse the text. What's the right way to parse this in Django? I wasn't able to find instructions on this in the documentation.
It depends on the actual content of your mail (plain or html) but the easy way is to also encode the string you are testing against.
# if you are testing HTML content
self.assertTextInHTML("My email's contents", mail.outbox[0].body)
# the string may need escaping the same way django escapes
from django.utils.html import escape
self.assertIn(escape("My email's contents"), mail.outbox[0].body)
I'm currently developing this in Python (with web.py) on Windows, and using latest Chrome.
Simple test:
User is shown a basic web form with a component.
When form is submitted, the content of this textarea is placed into a MySql table, unmodified.
Later, the user returns to edit their last submission.
I then present a new form, with the textarea populated directly from the database for modification - HTML is prevented from being processed so tags are displayed.
However, when re-displayed to the user, every line now has an extra (unwanted) line-break between each line.
How can I prevent this?
eg:
Submitted Text:
Line 1
Line 2
When re-displayed, the text looks like:
Line 1
Line 2
I'm aware that this is going to be some kind of CR LF issue but can't quite get to the solution.
I tried a conversion to <br /> but that just displays the <br /> text not an actual line break.
I don't really want to modify the text before putting it into the database either.
But I guess I do need something that would compensate for various OS that display line breaks differently.
I've read through many of the similar questions here, but they are primarily PHP, or talk about nl2br which wouldn't be a solution here anyway.
If you are using print to output the text, append a comma at the end of your statement to remove the new-line character.
e.g.
print 'Some Text',
It may be that a new-line is already in your printed text and doesn't require the extra appended one from print.
If not, try .rstrip('\n') on your string to remove any new-lines.
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.
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.
I'm trying to render a string into a javascript ( which usually works fine for me ) here's my code
HTML:
THE USER NAME IS : {{name}} has added app {{has_added_app}}
JAVA SCRIPT:
<script>
<!--
var userName = {{name}}
The html version works the javascript fails when I have tried the same rendering in javascript before and it worked.
var userName = {{name}}
Comes out when you view the HTML source as:
var userName = Bob
Which is an obvious mistake: missing quotes. But, simply putting quotes around it:
var userName = '{{name}}';
isn't good enough for the general case. What if the string contains a quote character, or a backslash, or a newline? Best case, your app falls over. Worst case, cross-site-scripting security hole. What's more a & or < character in the name won't come through properly either, as Django autoescape will probably assume it's in a non-CDATA HTML context and inappropriately &-escape them.
Use the escapejs filter instead:
var userName = '{{name|escapejs}}';
Alternatively use a JSON encoder to turn any basic datatype into JavaScript literal format, not just string. There's json in the standard library from 2.6, but note this doesn't escape the < character in strings, so for injecting code into a script element you'd have to escape that manually to prevent a </script> sequence ending the CDATA element prematurely.
comments for the javascript:
var userName = "{{name}}";
Remember that Django templates are purely textual: they don't "know" that you're creating Javascript. You need to include the quotes that Javascript needs around a string literal:
var userName = "{{name}}";