I want to create attributes on the fly for some html elements.
In my case I'd like to set (or not) a disabled attribute according to user.role.
So, if user has permission to edit some field, I do not want to put disabled attribute on the element. Otherwise, I do want it.
I know that I can do this with these approaches:
- Approach 1 - Use Conditionals
if (user.role === 1)
input(type='text', name='foo')
else
input(type='text', name='foo', disabled)
- Approach 2 - Plain HTML
- var disabledAttr = (user.role === 1) ? "disabled" : "";
| <input type="text" name="foo" #{ disabledAttr} />
Approach 1 is bad because I need to repeat some code. With Approach 2 I do not need to repeat code but I have to use plain HTML instead of Jade markup.
I tried something like this:
input(type='text', name='foo', #{ disabledAttr} )
But jade generates the following code:
<input type="text" name="foo" disabledattr="" />
Any better idea?
Jade is quite clever when it needs to figure out how to render attributes. You can render your disabled attribute using this single line of jade markup
input(type='text', name='foo', disabled=role!==1)
You can to use a bunch of attributes in a conditional way:
input(type='text')&attributes(user.role === 1 ? {'disabled': 'true'} : {'class': 'admin', 'ng-model': 'vm.model.name', 'ng-click': 'vm.click()'})
This syntax works for me:
input(placeholder!="<%= translate('Add new item') %>")
where translate is a function that returns translated text.
Related
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
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
I'm trying use input with datalist in a lightning component and doesn't seem to work. I've looked around and can't seem to find anything that says i can't. So basically,
<input list="acctlist"/>
<datalist id="acctlist">
<option value="somevalue">
</datalist>
does not work. I want to have an input in a form that a user can type but also able to select from a list returned from the controller. Is there a workaround that would be as simple or is this the following route the best i got.
https://developer.salesforce.com/blogs/developer-relations/2015/06/salesforce-lightning-inputlookup-missing-component.html
The list attribute of input tag is not compatible with lightning component.
When you deploy the components, the attribute is removed.
If you want to use input with datalist, you need to add the attribute in Renderer.js.
datalist.cmp
<input aura:id="acctlistInput" />
<datalist id="acctlist">
<option value="somevalue" />
</datalist>
datalistRenderer.js
afterRender : function(component, helper) {
var acctlistInputCmp = component.find("acctlistInput");
var acctlistInput = acctlistInputCmp.getElement();
acctlistInput.setAttribute("list", "acctlist");
return this.superAfterRender();
}
First of all, what is a viewstate?
In testautomation I probably need to correlate this value as it is unique for every user logging in?
How can I get the 'value' / token below using regex?
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTUxOTg3NDM2NGQYCAUkY3RsMDAkTWFpbk1lbnUkTWVudSRjdGwwMSRjdGwwMCRNZW51DxQrAA5kZGRkZGRkPCsABQACBWRkZGYC/////w9kBSRjdGwwMCRNYWluTWVudSRNZW51JGN0bDAzJGN0bDAwJE1lbnUPFCsADmRkZGRkZGQ8KwAEAAIEZGRkZgL/////D2QFJGN0bDAwJE1haW5NZW51JE1lbnUkY3RsMDQkY3RsMDAkTWVudQ8UKwAOZGRkZGRkZDwrAAcAAgdkZGRmAv////8PZAUkY3RsMDAkTWFpbk1lbnUkTWVudSRjdGwwNiRjdGwwMCRNZW51DxQrAA5kZGQCAmRkZDwrAAkAAglkZGRmAv////8PZAUkY3RsMDAkTWFpbk1lbnUkTWVudSRjdGwwMiRjdGwwMCRNZW51DxQrAA5kZGQCAmRkZDwrAAsAAgtkZGRmAv////8PZAUpY3RsMDAkRm9vdGVyUmVnaW9uJGN0bDAwJEZvb3RlckxpbmtzJExpc3QPD2ZkZAUTY3RsMDAkY3RsMDMkUnNzTGlzdA8PZmRkBSRjdGwwMCRNYWluTWVudSRNZW51JGN0bDA1JGN0bDAwJE1lbnUPFCsADmRkZGRkZGQ8KwAJAAIJZGRkZgL/////D2R3kjxauWd2eu+C/bmZz+/bI7YRkg==" />
Read this: RegEx match open tags except XHTML self-contained tags
then if you still want to have a go, use this:
(?<=input )(?:.*)(value\=\".*\")
Following on from an earlier question, I'm having problems using an Editor template for datetime fields, below is the code for the editor template (called "EditDateTime").
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%= Html.TextBox("", (Model.HasValue ? Model.Value.Date.ToString("dd/MMM/yyyy") :
DateTime.Today.ToString("dd/MMM/yyyy")), new { #class = "date" })%>
Here is the call to use the editor template,
<%=Html.EditorFor(Model => Model.StartDate, "EditDateTime") %>
All works ok, except the formatting is ignored. The Asp.Net MVC2 Framework book documents templates and specifically states
We’re passing an empty string for the name
parameter because the framework will automatically prefix this with the field name corresponding to the model item being rendered;
So I shouldnt need an id, so why is the formatting being ignored? HOWEVER - if I include an ID, the formatting is adhered to, BUT the model binding is then broken.
Help?
Just to clarify..
If I give the HMTL.Textbox an ID I get the following... The date format is correct but I lose the model binding as the ID is changed from "StartDate" to "StartDate_xx"
<input class="date" id="StartDate_xx" name="StartDate.xx" type="text" value="02/May/2012" />
And without the Id, it looks like this... model binding is correct but format is not.
<input class="date" id="StartDate" name="StartDate" type="text" value="05/02/2012 00:00:00" />
try using
Model.Value.ToString("dd/MM/yyyy")
works for me.
everything looks fine really... is the item you are sending a Datetime or a Datetime?