RactiveJS dynamic variable name - ractivejs

I'm curious if I can somehow use dynamic variable names in templates. For example, I'm having a loop, though a type of units in my game:
{{# config.units:unit }}
<input type="text" id="unit_{{unit}}" class="toTrain selectable" value="" placeholder="0" />
{{/ config }}
Where the value of the input should return the value of {{units_1}} for example, which represents the amount of units (type 1).
I could easily do some external object and store the amount of units for each of them but, I was wondering if I can keep the data binded because somewhere in the template there will be a total needed resources which is calculated whith these values.
The only "solution" which came into my head was to get rid of the loop and manually write the units in the template. But, when units change, I also need to change the template, and.. the real template structure for one unit is a bit bigger than this snippet.
Example:
<input value="{{units_1}}" />
<input value="{{units_2}}" />
And I was looking for something like:
<input value="{{'units_'+unit}}" />
Which is obviously not working and not even supposed to work this way. But, thats why I'm here right ? To raise questions.
Regards !

Try to use write getUnit function:
{{# config.units:unit }}
<input type="text" id="{{ getUnit(unit) }}" class="toTrain selectable" value="" placeholder="0" />
{{/ config }}
Component:
Ractive.extend({
init:function(){
self.set("getUnit", function (id) {
return self.get("config.units.unit_"+id);
});
}
})

Related

How to display date in an input with twig and symfony?

I can't store the actual day in my date input type.
When I set up the twig line to get the date, it works perfectly but then when I try to store it in my input it doesn't display it.
twig
{#This line provides the day of today#}
{{ "now"|date("d/m/Y") }}
twig
{#Then this line doesn't changes the value of the input#}
<input type="date" value="{{ "now"|date("d/m/Y") }}" class="form-control" name="date">
this is neither a twig nor a symfony problem...
the format for <input type="date">'s value is YYYY-mm-dd. The display is something different. <input type="date"> will format depending on user locale and stuff.
see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date

How do I handle a boolean HTML attribute in a Handlebars partial?

I'm writing a fun little project to build up my HTML/JS skills. I'm using Handlebars to render some forms, and I hit something I can't seem to get around.
I've registered this as a partial template named 'checkbox':
<label>
<input
type="checkbox"
id="{{id}}"
name="{{id}}"
value="true">
{{labelText}}
</label>
That did me well when I was making forms to add data, but now I'm making forms to edit data, so I want to make the checkbox checked if the current item already is checked. I can't figure out how to make this work.
The first thing I tried was something like this:
<label>
<input
type="checkbox"
id="{{id}}"
name="{{id}}"
value="true"
checked="{{isChecked}}">
{{labelText}}
</label>
But if I pass that values like isChecked=true I get a checked box every time, because I guess for that kind of attribute in HTML being present at all means 'true'. OK.
So I tried using the if helper:
<input
type="checkbox"
id="{{id}}"
name="{{id}}"
value="true"
{{#if isChecked}}checked{{/if}}>
{{labelText}}
This sort of works. If I omit the isChecked property entirely, the box is unchecked. If I hard-code a true or false value like this, it works:
{{> checkbox id="test" labelText="test" isChecked=true }}
But I can't seem to get what I want with a value there. For example, if I try:
{{> checkbox id="test" labelText="test" isChecked="{{someCondition}}" }}
It seems like the condition isn't properly being resolved because I always get the attribute in that case.
What am I missing? I feel like there should be a way to do this, but I'm running out of tricks.
You cannot put an expression inside of another expression:
{{> checkbox id="test" labelText="test" isChecked="{{someCondition}}" }}
From examples you wrote I assume the problem you are having is related to how you pass the context - id and labelText are hardcoded while isChecked is expected to be a variable of some sort. In reality all those should be variables. Consider the following example - HTML:
<div id="content"></div>
<script id="parent-template" type="text/x-handlebars-template">
{{#each checkboxes}}
{{> checkbox this }}<br>
{{/each}}
</script>
<script id="partial-template" type="text/x-handlebars-template">
<input
type="checkbox"
id="{{id}}"
name="{{id}}"
value="true"
{{#if isChecked}}checked{{/if}}>
{{labelText}}
</script>
JS:
var parentTemplate = Handlebars.compile($("#parent-template").html());
Handlebars.registerPartial({
checkbox: Handlebars.compile($("#partial-template").html())
});
$('#content').html(parentTemplate(
{checkboxes: [
{id: 1, labelText: "test 1", isChecked: true},
{id: 2, labelText: "test 2", isChecked: false},
]}
));

meteor template argument value differs between helper and event

I want to include a Blaze template with an argument and then use the argument value in an event. The problem is that when I include the template a second time with a different argument I get the argument value from the first instance of the template in events.
Template:
<template name="UploadFormLayoutImage">
<form class="uploadPanel">
<input type="file" name="fileupload" id="input-field">
<label for="input-field">Upload file</label>
</form>
</template>
Include:
{> UploadFormLayoutImage layoutArea="area1"}}
{> UploadFormLayoutImage layoutArea="area2"}}
js:
Template.UploadFormLayoutImage.onCreated(function(){
this.currentArea = new ReactiveVar;
this.currentArea.set(this.data.layoutArea);
});
Template.UploadFormLayoutImage.helpers({
layoutArea: function() {
return Template.instance().currentArea.get(); //Returns the correct argument value for each instance of the template.
}
});
Template.UploadFormLayoutImage.events({
'change input[type="file"]': function(e, instance) {
e.preventDefault();
console.log(instance.data.layoutArea); //Allways returns 'area1'
}
});
What am I missing here? (This is my first Stackoverflow question. Please be gentle :))
What if you change the instance.data.layoutArea in your events method to this.layoutArea?
In my effort to make the code example easy to read i stripped away the part that caused the problem. I'm using a label for the input field and therefore the input field has an id and thats of course not ok when repeating the template.
I now use the layoutArea-helper as an id value and every thing works just fine.
<template name="UploadFormLayoutImage">
<form class="uploadPanel">
<input type="file" name="fileupload" id="{{layoutArea}}">
<label for="{{layoutArea}}">Upload file</label>
</form>
</template>

How to render a checkbox group with fields from an Entity with Symfony2

I have a material table that is related to items_budget. The form for items_budget needs to list all the registered material as a checkbox group, and beside each checkbox, two input fields, for quantity and price. Below is the code block I wrote for rendering this piece:
<strong>Materiais</strong>
{% for material in materials %}
<div class="checkbox">
<label>
<input type="checkbox" class="itemsbudget_material" name="cdg_itemsbudget_type[material]" value="{{ material.id }}"> {{ material.name }} -
</label>
<input type="hidden" class="itemsbudget_price_hidden" value="{{ material.price }}"/>
<input type="text" class="itemsbudget_quantity" name="cdg_itemsbudget_type[quantity]" placeholder="Qtd" size="3"/>x - R$
<input type="text" class="itemsbudget_price" name="cdg_itemsbudget_type[price]" value="0" size="3" readonly/>
</div>
{% endfor %}
The problem I am facing can be seen in the image. Looking at the top-left image, you see I have marked "Material C", filled the quantity, and after submitting the form, as shown in the second image, everything is fine.
But if I do the same with another Material, as it can be seen in the last image of my table, the quantity field is NULL.
What happens here is that only the first register in the material form is, let's say, "seen". When I say "first register" I mean the lowest id in the material form, literally the FIRST. If I had deleted the "Material C", then "Material D" would be the first and the quantity field would be seen for it only.
I have tried to put at the end of each name attribute a pair of brackets, but by doing it the page is refreshed and nothing is persisted, nothing happens.
I have tried many different ways to render this. Also, I have tried to create my material field as a collection, but I really think this is not the solution because I must get the id, quantity and price entered in the fields. I would need to be able to render something exactly like this with a collection form.
Please I need guidance. If you need any more code I will be happy to update my question. Thank you.
The value of quantity field is null, because the name of field is cdg_itemsbudget_type[quantity], the value override by last quantity field which is empty, the name of your field must be array with unique index something like this:
<input type="text" class="itemsbudget_quantity" name="cdg_itemsbudget_type[quantity][{{ material.id }}]" placeholder="Qtd" size="3"/>x - R$
And then you have array of quantity for each material.

CSS styling in Django forms

I would like to style the following:
forms.py:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)
contact_form.html:
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
For example, how do I set a class or ID for the subject, email, message to provide an external style sheet to?
Taken from my answer to:
How to markup form fields with <div class='field_type'> in Django
class MyForm(forms.Form):
myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'}))
or
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})
or
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
}
--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented
-- EDIT 2 ---
Added a newer way to specify widget and attrs for a ModelForm.
This can be done using a custom template filter. Consider rendering your form this way:
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
{{ form.subject.label_tag }}
{{ form.subject }}
<span class="helptext">{{ form.subject.help_text }}</span>
</div>
</form>
form.subject is an instance of BoundField which has the as_widget() method.
You can create a custom filter addclass in my_app/templatetags/myfilters.py:
from django import template
register = template.Library()
#register.filter(name='addclass')
def addclass(value, arg):
return value.as_widget(attrs={'class': arg})
And then apply your filter:
{% load myfilters %}
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
{{ form.subject.label_tag }}
{{ form.subject|addclass:'MyClass' }}
<span class="helptext">{{ form.subject.help_text }}</span>
</div>
</form>
form.subjects will then be rendered with the MyClass CSS class.
If you don't want to add any code to the form (as mentioned in the comments to #shadfc's Answer), it is certainly possible, here are two options.
First, you just reference the fields individually in the HTML, rather than the entire form at once:
<form action="" method="post">
<ul class="contactList">
<li id="subject" class="contact">{{ form.subject }}</li>
<li id="email" class="contact">{{ form.email }}</li>
<li id="message" class="contact">{{ form.message }}</li>
</ul>
<input type="submit" value="Submit">
</form>
(Note that I also changed it to a unsorted list.)
Second, note in the docs on outputting forms as HTML, Django:
The Field id, is generated by
prepending 'id_' to the Field name.
The id attributes and tags are
included in the output by default.
All of your form fields already have a unique id. So you would reference id_subject in your CSS file to style the subject field. I should note, this is how the form behaves when you take the default HTML, which requires just printing the form, not the individual fields:
<ul class="contactList">
{{ form }} # Will auto-generate HTML with id_subject, id_email, email_message
{{ form.as_ul }} # might also work, haven't tested
</ul>
See the previous link for other options when outputting forms (you can do tables, etc).
Note - I realize this isn't the same as adding a class to each element (if you added a field to the Form, you'd need to update the CSS also) - but it's easy enough to reference all of the fields by id in your CSS like this:
#id_subject, #id_email, #email_message
{color: red;}
Per this blog post, you can add css classes to your fields using a custom template filter.
from django import template
register = template.Library()
#register.filter(name='addcss')
def addcss(field, css):
return field.as_widget(attrs={"class":css})
Put this in your app's templatetags/ folder and you can now do
{{field|addcss:"form-control"}}
You can do like this:
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
subject.widget.attrs.update({'id' : 'your_id'})
Hope that works.
Ignas
You could use this library: https://pypi.python.org/pypi/django-widget-tweaks
It allows you to do the following:
{% load widget_tweaks %}
<!-- add 2 extra css classes to field element -->
{{ form.title|add_class:"css_class_1 css_class_2" }}
Write your form like:
class MyForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attr={'class':'name'}),label="Your Name")
message = forms.CharField(widget=forms.Textarea(attr={'class':'message'}), label="Your Message")
In your HTML field do something like:
{% for field in form %}
<div class="row">
<label for="{{ field.name}}">{{ field.label}}</label>{{ field }}
</div>
{% endfor %}
Then in your CSS write something like:
.name{
/* you already have this class so create it's style form here */
}
.message{
/* you already have this class so create it's style form here */
}
label[for='message']{
/* style for label */
}
Hope this answer is worth a try! Note you must have written your views to render the HTML file that contains the form.
You can do:
<form action="" method="post">
<table>
{% for field in form %}
<tr><td>{{field}}</td></tr>
{% endfor %}
</table>
<input type="submit" value="Submit">
</form>
Then you can add classes/id's to for example the <td> tag. You can of course use any others tags you want. Check Working with Django forms as an example what is available for each field in the form ({{field}} for example is just outputting the input tag, not the label and so on).
Didn't see this one really...
https://docs.djangoproject.com/en/1.8/ref/forms/api/#more-granular-output
More granular output
The as_p(), as_ul() and as_table() methods are simply shortcuts for lazy developers – they’re not the only way a form object can be displayed.
class BoundField
Used to display HTML or access attributes for a single field of a Form instance.
The str() (unicode on Python 2) method of this object displays the HTML for this field.
To retrieve a single BoundField, use dictionary lookup syntax on your form using the field’s name as the key:
>>> form = ContactForm()
>>> print(form['subject'])
<input id="id_subject" type="text" name="subject" maxlength="100" />
To retrieve all BoundField objects, iterate the form:
>>> form = ContactForm()
>>> for boundfield in form: print(boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" />
<input type="text" name="message" id="id_message" />
<input type="email" name="sender" id="id_sender" />
<input type="checkbox" name="cc_myself" id="id_cc_myself" />
The field-specific output honors the form object’s auto_id setting:
>>> f = ContactForm(auto_id=False)
>>> print(f['message'])
<input type="text" name="message" />
>>> f = ContactForm(auto_id='id_%s')
>>> print(f['message'])
<input type="text" name="message" id="id_message" />
One solution is to use JavaScript to add the required CSS classes after the page is ready. For example, styling django form output with bootstrap classes (jQuery used for brevity):
<script type="text/javascript">
$(document).ready(function() {
$('#some_django_form_id').find("input[type='text'], select, textarea").each(function(index, element) {
$(element).addClass("form-control");
});
});
</script>
This avoids the ugliness of mixing styling specifics with your business logic.
You may not need to override your form class' __init__, because Django sets name & id attributes in the HTML inputs. You can have CSS like this:
form input[name='subject'] {
font-size: xx-large;
}
There is a very easy to install and great tool made for Django that I use for styling and it can be used for every frontend framework like Bootstrap, Materialize, Foundation, etc. It is called widget-tweaks Documentation: Widget Tweaks
You can use it with Django's generic views
Or with your own forms:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)
Instead of using default:
{{ form.as_p }} or {{ form.as_ul }}
You can edit it your own way using the render_field attribute that gives you a more html-like way of styling it like this example:
template.html
{% load widget_tweaks %}
<div class="container">
<div class="col-md-4">
{% render_field form.subject class+="form-control myCSSclass" placeholder="Enter your subject here" %}
</div>
<div class="col-md-4">
{% render_field form.email type="email" class+="myCSSclassX myCSSclass2" %}
</div>
<div class="col-md-4">
{% render_field form.message class+="myCSSclass" rows="4" cols="6" placeholder=form.message.label %}
</div>
</div>
This library gives you the opportunity to have well separated yout front end from your backend
In Django 1.10 (possibly earlier as well) you can do it as follows.
Model:
class Todo(models.Model):
todo_name = models.CharField(max_length=200)
todo_description = models.CharField(max_length=200, default="")
todo_created = models.DateTimeField('date created')
todo_completed = models.BooleanField(default=False)
def __str__(self):
return self.todo_name
Form:
class TodoUpdateForm(forms.ModelForm):
class Meta:
model = Todo
exclude = ('todo_created','todo_completed')
Template:
<form action="" method="post">{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.todo_name.errors }}
<label for="{{ form.name.id_for_label }}">Name:</label>
{{ form.todo_name }}
</div>
<div class="fieldWrapper">
{{ form.todo_description.errors }}
<label for="{{ form.todo_description.id_for_label }}">Description</label>
{{ form.todo_description }}
</div>
<input type="submit" value="Update" />
</form>
For larger form instead of writing css classed for every field you could to this
class UserRegistration(forms.ModelForm):
# list charfields
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2')
def __init__(self, *args, **kwargs):
super(UserRegistration, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'form-control'
Edit: Another (slightly better) way of doing what I'm suggesting is answered here: Django form input field styling
All the above options are awesome, just thought I'd throw in this one because it's different.
If you want custom styling, classes, etc. on your forms, you can make an html input in your template that matches your form field. For a CharField, for example, (default widget is TextInput), let's say you want a bootstrap-looking text input. You would do something like this:
<input type="text" class="form-control" name="form_field_name_here">
And as long as you put the form field name matches the html name attribue, (and the widget probably needs to match the input type as well) Django will run all the same validators on that field when you run validate or form.is_valid() and
Styling other things like labels, error messages, and help text don't require much workaround because you can do something like form.field.error.as_text and style them however you want. The actual fields are the ones that require some fiddling.
I don't know if this is the best way, or the way I would recommend, but it is a way, and it might be right for someone.
Here's a useful walkthrough of styling forms and it includes most of the answers listed on SO (like using the attr on the widgets and widget tweaks).
https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html
Styling widget instances
If you want to make one widget instance look different from another, you will need to specify additional attributes at the time when the widget object is instantiated and assigned to a form field (and perhaps add some rules to your CSS files).
https://docs.djangoproject.com/en/2.2/ref/forms/widgets/
To do this, you use the Widget.attrs argument when creating the widget:
class CommentForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
url = forms.URLField()
comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))
You can also modify a widget in the form definition:
class CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField()
name.widget.attrs.update({'class': 'special'})
comment.widget.attrs.update(size='40')
Or if the field isn’t declared directly on the form (such as model form fields), you can use the Form.fields attribute:
class CommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'special'})
self.fields['comment'].widget.attrs.update(size='40')
Django will then include the extra attributes in the rendered output:
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" class="special" required></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40" required></td></tr>
I was playing around with this solution to maintain consistency throughout the app:
def bootstrap_django_fields(field_klass, css_class):
class Wrapper(field_klass):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def widget_attrs(self, widget):
attrs = super().widget_attrs(widget)
if not widget.is_hidden:
attrs["class"] = css_class
return attrs
return Wrapper
MyAppCharField = bootstrap_django_fields(forms.CharField, "form-control")
Then you don't have to define your css classes on a form by form basis, just use your custom form field.
It's also technically possible to redefine Django's forms classes on startup like so:
forms.CharField = bootstrap_django_fields(forms.CharField, "form-control")
Then you could set the styling globally even for apps not in your direct control. This seems pretty sketchy, so I am not sure if I can recommend this.

Resources