Add a newline after each closing html tag in web2py - regex

Original
I want to parse a string of html code and add newlines after closing tags + after the initial form tag. Here's the code so far. It's giving me an error in the "re.sub" line. I don't understand why the regex fails.
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
result = re.sub("(</.*?>)", "\1\n", tags)
return dict(form_code=result)
PS. I have a feeling this might not be the best way... but I still want to learn how to do this.
EDIT
I was missing "import re" from my default.py. Thanks ruakh for this.
import re
Now my page source code shows up like this (inspected in client browser). The actual page shows the form code as text, not as UI elements.
<form><label for="email_field">Email:</label>
<input type="email" name="email_field"/><label
for="password_field">Password:</label>
<input type="password" name="password_field"/><input
type="submit" value="Login"/></form>
EDIT 2
The form code is rendered as UI elements after adding XML() helper into default.py. Thanks Anthony for helping. Corrected line below:
return dict(form_code=XML(result))
FINAL EDIT
Fixing the regex I figured myself. This is not optimal solution but at least it works. The final code:
import re
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
tags = re.sub(r"(<form>)", r"<form>\n ", tags)
tags = re.sub(r"(</.*?>)", r"\1\n ", tags)
tags = re.sub(r"(/>)", r"/>\n ", tags)
tags = re.sub(r"( </form>)", r"</form>\n", tags)
return dict(form_code=XML(tags))

The only issue I see is that you need to change "\1\n" to r"\1\n" (using the "raw" string notation); otherwise \1 is interpreted as an octal escape (meaning the character U+0001). But that shouldn't give you an error, per se. What error-message are you getting?

By default, web2py escapes all text inserted in the view for security reasons. To avoid that, simply use the XML() helper, either in the controller:
return dict(form_code=XML(result))
or in the view:
{{=XML(form_code)}}
Don't do this unless the code is coming from a trusted source -- otherwise it could contain malicious Javascript.

Related

Trying to render a django form field as a variable in a script tag in an html template, but the javascript isn't working

My issue is simple enough--I am trying to render a form field from a django form into a javascript variable, defined within a <script> tag, within a django template.
When I output a CharField, there's no problem. But when I try to render a ChoiceField, the resulting output breaks the html, and prevents the script tag from correctly parsing my variable.
To demonstrate my setup, I have a form defined in forms.py, exactly like this example form:
from django import forms
form = TestForm(forms.Form):
testfield = forms.ChoiceField(initial="increase_rate",
choices=[
("a", "option a"),
("b", "option b"),
("c", "option c"),
("d", "option d")
])
I am instantiating the form in views.py, and passing it into a django template to be rendered.
from django.shortcuts import render
from .forms import TestForm
[...]
#require_http_methods(["GET"])
def webpage(request):
form = TestForm()
return render(request, 'index.html', {"form":form})
Then, finally, in my template, I have something like the following:
[...]
<script>
window.testfield = '{{ form.testfield }}'
</script>
[...]
Up until this point, everything works perfectly. No trouble at all. But when I render the field into the template, and inspect it in my browser, I get the following:
<script>
window.testfield = '<select name="trigger" id="id_trigger">
<option value="a" selected>option a</option>
<option value="b">option b</option>
<option value="c">option c</option>
<option value="d">option d</option>
</select>'
</script>
This output breaks the html, and prevents the script tag from being interpreted as a variable like I want. This is a major problem, because I want to reuse these programmatically elsewhere on the page.
I tried the following:
<script>
window.testfield = '{{ form.testfield|escape }}'
</script>
But was still unsuccessful. Any help anyone can give would be greatly appreciated!
I am actively researching a solution. My current guess is that the output needs to be escaped somehow that I don't understand. I figure the template tags and filters have my answer, I just have to find it. Will post an update once a solution is found.
Use <script type="text/template"></script>.
This way the browser knows it's just text and will ignore it.
So, I figured it out. Turns out that the issue was that the presence of white space, line breaks, and unescaped double quotes (") were breaking the tag when it was parsed at HTML.
So I ended up using the following:
{% spaceless %}
<script>
window.testfield = '{{ form.testfield|addslashes }}'
</script>
{% endspaceless %}
And it worked, allowing me to store the string representation of the django form field in a javascript variable. As per the documentation, the {% spaceless %} "Removes whitespace between HTML tags. This includes tab characters and newlines." [1]. As for the filter |addslashes, it "Adds slashes before quotes. Useful for escaping strings in CSV" [2]. In my case, both solutions were needed, as without either of them, the script tag broke.
As for why the |escape filter didn't work on it's own, I'm not sure. Reading the documentation, it seems like it probably should have. The following is what the |escape filter actually does [3]:
Escapes a string’s HTML. Specifically, it makes these replacements:
< is converted to <
> is converted to >
' (single quote) is converted to '
" (double quote) is converted to "
& is converted to &
I can only guess why this didn't work. I figure it's because it didn't do anything about the white space. But I shouldn't speculate. I welcome any explanations you might have. As ever, understanding the way the machine thinks is better than any single, specific solution. Thanks.
[1] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless
[2] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#addslashes
[3] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape

Angular2 - Why does my reactive form input with an html pattern attribute is not validating correctly?

I'm struggling with a problem that I can't understand:
I need to validate an input field with a pattern="[0-9]+([,.][0-9])?" attribute on an angular reactive form with Validators.pattern, but it seems my ? quantifier at the end is not working...
What I want
I want to validate numbers with zero or one decimal maximum. As you can see on https://regex101.com/r/2D2sww/1, the regex is working great.
The actual problem
In my app I can enter as many decimals as I want without the Validator.pattern to do anything. Any other character invalidate the form, so my Validator is working.
Here is my code (simplified):
component.html
<form [formGroup]="myForm">
<input type="number" formControlName="myInputField" id="myInputField" pattern="[0-9]+([,.][0-9])?" required />
</form>
component.ts (Every import and declarations are skipped for clarity)
ngOnInit() {
this.myForm = this.formBuilder.group({
myInputField: [
"",
[Validators.required, Validators.pattern],
]
});
}
I already tried to use Validators.pattern(/^[0-9]+([,.][0-9])?$/) and Validators.pattern("[0-9]+([,.][0-9])?") as pointed in the documentation, but it doesn't change anything, so I suspect my Regex to be incorrect...
Any ideas ? Thanks, have a nice day :)
I think there is nothing wrong with your validator pattern regex,
you can remove the pattern's attribute from the input, it is redundant because you are initiating it from inside the ts file: 'myInputField': new FormControl(null, [Validators.pattern('^[0-9]+([,.][0-9])?$')]).
StackBlitz

How to show code snippet in django template, "|safe" filter not helps

I'm trying to make app like gist.github.com. After saving code snippets they looks in like long string. I tried different filters like "safe, escape ... etc". Nothing helped me.
In database code looks like:
def asd(a):
return a+2
asd(2)
This is my template code:
<div>{{ s.code|escape }}</div>
Result is:
def asd(a): return a+2 asd(2)
This doesn't have anything to do with escaping or marking as safe. In fact, it doesn't have anything to do with Django at all.
HTML ignores whitespace, including newlines. If you want to show your code as formatted in the db you should use the <pre> tag.

New Line on Django admin Text Field

I am trying to create a blog o django where the admin posts blogs from the admin site.
I have given a TextField for the content and now want to give a new line.
I have tried using \n but it doesn't help. The output on the main html page is still the same with \n printing in it. I have also tried the tag and allowed tags=True in my models file. Still the same. All the tags are coming as it is on the html page.
My Django admin form submitted:
The result displayed in my public template:
You should use the template filter linebreaks, that will convert the reals \n (that means the newline in the textarea, not the ones you typed using \ then n) into <br />:
{{ post.content|linebreaks }}
Alternatively, you can use linebreaksbr if you don't want to have the surrounding <p> block of course.
After searching the internet and trying different Django Template Filters, I came across one specific filter, SAFE.
For me, LINEBREAKS filter didn't work, as provided by #Maxime above, but safe did.
Use it like this in your html template file.
{{post.content|safe}}
To have a better understanding of SAFE filter, i suggest reading the documentation.
{{post.content|linebreaks}}
This will make the line in the textbox appear as it is without using \n or \.
{{post.content|linebreaksbr}}
Besides the newline function in your CSS Declaration will work too.

Hyperlinks inside object fields

I have an object inside my Ember app, with a description field. This description field may contain hyperlinks, like this
My fancy text <a href='http://other.site.com' target='_blank'>My link</a> My fancy text continues...
However, when i output it normally, like {{ description }} my hyperlinks are displayed as a plain text. Why is this happening and how can i fix this?
Handlebars escapes any HTML within output by default. For unescaped text in markup use triple-stashes:
{{{ description }}}
There's an alternative when one controls the property: Handlebars.SafeString. SafeStrings are assumed to be safe and are not escaped either. From the documentation:
Handlebars.registerHelper('link', function(text, url) {
text = Handlebars.Utils.escapeExpression(text);
url = Handlebars.Utils.escapeExpression(url);
var result = '' + text + '';
return new Handlebars.SafeString(result);
});
Note - please be careful with this. There are security concerns with rendering unescaped text that has come from user input; an attacker could inject a malicious script into the description and hijack your page, for example.