How to disable indentation on multiline html string - webstorm

How could I get rid of the WebStorm (re-format) indentation?
// Expected
template: $template(
'<div>' +
'<label> {{currentLength}} </label> ' +
'</div>'
)
// Not expected, after applying WebStorm auto format(indentation)
template: $template(
'<div>' +
'<label> {{currentLength}} </label> ' +
'</div>')

I don't think this will be possible to implement in the form you're suggesting – indenting the parent language expressions (JavaScript) in order to adhere to indenting rules for child (HTML) language. As a workaround, you can turn your multiline string into a template string (with backticks) and add //language=HTML comment to get HTML injected and auto-formatted:
//language=HTML
template: $template(
`<div>
<label> {{currentLength}} </label>
</div>`)

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

Data style property to Jinja2 "invalid syntax"

I am trying to convert a bootstrap multiple selector into Jinja2, but whenever I add data-style property to the form field badges = SelectMultipleField('Categorii proiect', choices=[(1, 'January'), (2,'February')]) I get invalid syntax.
Bootstrap multiple selector
<select multiple class="form-control selectpicker" data-style="btn btn-link" id="exampleFormControlSelect2">
<option>January</option>
<option>February</option>
</select>
Jinja2 template that works
{{ form.badges(class="form-control selectpicker", id="exampleFormControlSelect2") }}
Jinja2 template that fails
{{ form.badges(class="form-control selectpicker", data-style="btn btn-link", id="exampleFormControlSelect2") }}
Any suggestion would be highly appreciated!
that's because data-style is not a valid parameter's name (there's - dash character) passed to the function.
a valid name has to be Alphanumeric, _ the underscore character is allowed, -, #, # .. are not allowed
to counter the invalid syntax error you need to pass that parameter and any extra parameters (if any) through the **kwrgs object like
{{ form.badges(class="form-control selectpicker", id="exampleFormControlSelect2", **{"data-style":"btn btn-link" }) }}

HTML - Using pattern attribute

In html form, I need textarea which allows any type of text: numbers, symbols, newline or letters, including Hebrew letters. The only two rules:
The input must include the string: "{ser}"
The input should prohibit any use of "{" or "}" except for the above string
I tried this:
<form action="#">
...
<textarea pattern="[^\{\}]*\{ser\}[^\{\}]*" required>
האם אתה נמצא בשבת הקרובה? אם כן נא השב {ser} + שם מלא
</textarea>
...
<input type="submit" />
...
</form>
But for some reason it also allows sending texts that do not meet the rules. I would appreciate your help.
You cannot use pattern attribute on textareas, see the documentation.
maxlength specifies a maximum number of characters that the
is allowed to contain. You can also set a minimum length that is
considered valid using the minlength attribute, and specify that the
will not submit (and is invalid) if it is empty, using the
required attribute. This provides the with simple
validation, which is more basic than the other form elements (for
example, you can't provide specific regexs to validate the value
against using the pattern attribute, like you can with the input
element).
Perhaps implement a regex match with javascript?
function validateTextarea(text) {
var re = /ser/g;
var result = text.match(re);
if(result != null && result.length > 0)
// Do something
}
Then probably the best way is to check the function in onsubmit form attribute.

RegExp replace all but selected

So I'm trying to erase everything except the matched case in this 1900 line document with Notepad++ RegExp Find/Replace, so that I only have the file names, which shorten it to under about 1000 lines at minimum. I know the code that selects the text ((?<=/images/item/)(.*)(?=" a) but the problem is I don't know how to make it erase anything that doesn't match that case. Here's a portion of the document.
using notepad++, it would find and select abyssal-scepter.gif, aegis-of-the-legion.gif, etc
<img src="/images/item/abyssal-scepter.gif" alt="LoL Item: Abyssal Scepter"><br> <div id="id_77" class="tier-wrapper drag-items health magic-resist health-regen champ-box float-left ajax-tooltip {t:'Item',i:'77'} classic-and-dominion filter-is-dominion filter-is-classic filter-tier-advanced filter-bonus-aura filter-category-health filter-category-magic-resist filter-category-health-regen ui-draggable ui-draggable-handle">
<img src="/images/item/aegis-of-the-legion.gif" alt="LoL Item: Aegis of the Legion"><br> <div id="id_235" class="tier-wrapper drag-items ability-power movement champ-box float-left ajax-tooltip {t:'Item',i:'235'} filter-tier-advanced filter-bonus-unique-passive filter-category-ability-power filter-category-movement ui-draggable ui-draggable-handle">
<img src="/images/item/aether-wisp.gif" alt="LoL Item: Aether Wisp"><br>
<div class="info">
<div class="champ-name">Aether Wisp</div>
<div class="champ-sub">
<img src="/images/gold.png" alt="Item Cost" style="width:16px; vertical-align:middle;"> 850 / 415
</div>
</div>
</div>
<div id="id_21" class="tier-wrapper drag-items ability-power champ-box float-left ajax-tooltip {t:'Item',i:'21'} classic-and-dominion filter-is-dominion filter-is-classic filter-tier-basic filter-category-ability-power ui-draggable ui-draggable-handle">
<img src="/images/item/amplifying-tome.gif" alt="LoL Item: Amplifying Tome"><br>
<div class="info">
<div class="champ-name">Amplifying Tome</div>
<div class="champ-sub">
I'm not familiar with RegExp, so to summarize, I need it to look like this at the end of it.
abyssal-scepter.gif
aegis-of-thelegion.gif
aether-wisp.gif
amplifying-tome.gif
Thank you for your time
A Notepad++ solution:
Find what : .*?/images/item/(.*?)"|.*
Replace with : $1\n
Search mode : Regular expression (with ". matches newline" checked)
The result will have an extra linefeed at the end.
But that shouldn't pose a problem I suppose.
Maybe this can help. or not since you dropped the Javascript tag out of your original post
<script type="text/javascript">
var thestring = "<img src=\"/images/item/aegis-of-the-legion.gif\" alt=\"LoL Item: Aegis of the Legion\"><br>";
var thestring2 = "<img src=\"/images/otherstuff/aegis-of-the-legion.gif\" alt=\"LoL Item: Aegis of the Legion\"><br>";
function ParseIt(incomingstring) {
var pattern = /"\/images\/item\/(.*)" /;
if (pattern.test(incomingstring)) {
return pattern.exec(incomingstring)[1];
}
else {
return "";
}
//return pattern.test(incomingstring) ? pattern.exec(incomingstring)[1] : "";
}
</script>
Calling ParseIt(thestring) returns "aegis-of-the-legion.gif"
Calling ParseIt(thestring2) return ""
Since you are doing this in NP++, this works for me. In cases like this where speed and results are more important than specific technique, I'll usually run several regexes. First, I'll get each tag on its own line by doing a search for > and replacing it with >\n. This gets each tag on its own line for simpler processing. Then a replace of ^>*<.*?".*?/?([\w\d\-_]+\.\w{2,4})?".*>.*$ with $1 will will extract all the filenames from the tags, removing the unneeded text. Then, finally, to clear all the tags that didn't have a filename in them, just replace <.*> with an empty string. Finally, use Edit>Line Operations>Remove empty lines, and you'll have the result you're looking for. It's not a 100% regex solution, but this is a one time action that you just need a simple result from.

Can I avoid this syntax highlighting confusion?

I have the following in my Django view:
<a title="{{ photo.time_taken|date:"N jS, 'y" }}" href='...' > {# ' #}
...
</a>
The problem is with wanting to format my date with the year as '13. The quotes get all confused, so I've had to put a django comment on the end to 'close' the quote, otherwise all following code is mis-highlighted. Is there a better way around this?
I'm using Sublime Text 2, with Djaneiro.