Text label is not aligning with form boxes from layout - symfony

I've been following Symfony2 documentation on how to override a Twig form template which is working however there is one problem. The names of the fields are not lining up next to the form boxes.
I should be getting this:
But instead my Name and Email labels are not aligning. I get this:
Can someone show me what I'm doing wrong? (I've copied over the code from the template and wrapped the form code with it.)
Overridden template code
{% block form_widget_simple %}
<div class="row collapse">
<div class="large-2 columns">
<label class="inline"></label>
</div>
<div class="large-10 columns">
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endspaceless %}
</div>
</div>
{% endblock form_widget_simple %}
{% block email_widget %}
<div class="row collapse">
<div class="large-2 columns">
<label class="inline"></label>
</div>
<div class="large-10 columns">
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endspaceless %}
</div>
</div>
{% endblock email_widget %}
{% block textarea_widget %}
{% spaceless %}
<textarea rows="12" {{ block('widget_attributes') }}>{{ value }}</textarea>
{% endspaceless %}
{% endblock textarea_widget %}
Original Zurb Foundation template code http://foundation.zurb.com/templates/contact.html
<form>
<div class="row collapse">
<div class="large-2 columns">
<label class="inline">Your Name</label>
</div>
<div class="large-10 columns">
<input type="text" id="yourName" placeholder="Jane Smith">
</div>
</div>
<div class="row collapse">
<div class="large-2 columns">
<label class="inline"> Your Email</label>
</div>
<div class="large-10 columns">
<input type="text" id="yourEmail" placeholder="jane#smithco.com">
</div>
</div>
<label>What's up?</label>
<textarea rows="4"></textarea>
<button type="submit" class="radius button">Submit</button>
</form>

Thanks to Michael Sivolobov for his guidance. Hope this helps others with the same question. Overwrote form_row and wrapped {{ form_label(form) }} in the <div class>.
% block form_row %}
{% spaceless %}
<div>
<div class="large-2 columns">
<label class="inline">{{ form_label(form) }}</label>
</div>
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock form_row %}

Related

How to modify Bootstrap 4 form validation information presentation in Django?

I am using Django and Bootstrap 4. I want to customize the way form validation information is displayed in a template I am using. When an error occurs in the current template, the invalid input element has a red outline and the error message is displayed as a pop-up. Also, the input elements that have been inputted correctly don't have a green outline, they just remain without an outline.
I'd like to do the following:
display the error message underneath the field when an error occurs
give the green outline to the fields whose input is correct
I tried multiple solutions, including:
this tutorial
this GitHub gist
the Stack Overflow answers from this question
None worked from my case.
My current code:
submit_job_listing.html (the template):
{% extends "base.html" %}
{% block title %} Submit a job {% endblock %}
{% block nav_item_post_a_job %}active{% endblock nav_item_post_a_job %}
{% block head %}
{{ job_listing_form.media.css }}
{% endblock %}
{% block content %}
<h1>Submit a job listing</h1>
<div class="container">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row text-center">
<h2> <b>Job listing information</b> </h2>
</div>
<br/>
{% for field in job_listing_form.visible_fields %}
<div class="form-group">
<div class="row">
<p>{{ field.label_tag }}</p>
</div>
<div class="row">
{% if field.help_text %}
<p class="form-text text-muted">{{ field.help_text }}</p>
{% endif %}
</div>
<div class="row">
{{ field }}
</div>
</div>
{% endfor %}
<br/>
<div class="row text-center">
<h2> <b>Employer information</b> </h2>
</div>
<br/>
{% for field in employer_form.visible_fields %}
<div class="form-group">
<div class="row">
<p>{{ field.label_tag }}</p>
</div>
<div class="row">
{% if field.help_text %}
<p class="form-text text-muted">{{ field.help_text }}</p>
{% endif %}
</div>
<div class="row">
{{ field }}
</div>
</div>
{% endfor %}
<input type="submit" value="Submit" class="btn btn-primary" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{{ job_listing_form.media.js }}
</div>
{% endblock %}
views.py (relevant parts):
def submitJobListing(request):
if request.method == "POST":
employer_form = EmployerForm(request.POST, request.FILES)
job_listing_form = JobListingForm(request.POST, request.FILES)
#check if employer with that name already exists
employer_name = str(request.POST.get("name", ""))
try:
employer_with_the_same_name = Employer.objects.get(name=employer_name)
except ObjectDoesNotExist:
employer_with_the_same_name = None
employer = None
if (employer_with_the_same_name != None):
employer = employer_with_the_same_name
if employer == None and employer_form.is_valid() and job_listing_form.is_valid():
employer = employer_form.save()
job_listing = job_listing_form.save(commit=False)
job_listing.employer = employer
job_listing.save()
job_listing_form.save_m2m()
return SimpleTemplateResponse("employers/successful_job_listing_submission.html")
else:
employer_form = EmployerForm()
job_listing_form = JobListingForm()
context = {
"employer_form": employer_form,
"job_listing_form": job_listing_form,
}
return render(request, 'employers/submit_job_listing.html', context)
forms.py (relevant parts):
class EmployerForm(forms.ModelForm):
name = forms.CharField(max_length=100)
#location = forms.CharField(widget=LocationWidget)
short_bio = forms.CharField(widget=forms.Textarea)
website = forms.URLField()
profile_picture = forms.ImageField()
def __init__(self, *args, **kwargs):
super(EmployerForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
if isinstance(visible.field.widget, (forms.widgets.TextInput, forms.widgets.Textarea, forms.widgets.URLInput, LocationWidget)):
visible.field.widget.attrs['class'] = 'form-control'
if isinstance(visible.field.widget, forms.widgets.ClearableFileInput):
visible.field.widget.attrs['class'] = 'form-control-file'
class Meta:
model = Employer
fields = ["name", "short_bio", "website", "profile_picture"]
class JobListingForm(forms.ModelForm):
job_title = forms.CharField(max_length=100, help_text="What's the job title?")
job_description = forms.CharField(widget=forms.Textarea)
job_requirements = forms.CharField(widget=forms.Textarea)
what_we_offer = forms.CharField(widget=forms.Textarea)
location = forms.CharField(widget=LocationWidget)
remote = forms.BooleanField()
job_application_url = forms.URLField()
point_of_contact = forms.EmailField()
categories = forms.ModelMultipleChoiceField(
queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple,
required=True)
def __init__(self, *args, **kwargs):
super(JobListingForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
if isinstance(visible.field.widget, (forms.widgets.TextInput, forms.widgets.Textarea, forms.widgets.URLInput, forms.widgets.EmailInput, LocationWidget)):
visible.field.widget.attrs['class'] = 'form-control'
if isinstance(visible.field.widget, (forms.widgets.CheckboxInput, forms.widgets.CheckboxSelectMultiple)):
visible.field.widget.attrs['class'] = 'form-check'
class Meta:
model = JobListing
fields = ["job_title", "job_description", "job_requirements", "what_we_offer", "location", "remote", "job_application_url", "categories", "point_of_contact"]
Can someone tell me how can I achieve the effects that I want?
Update 1:
I tried adding the code that checks for field.errors, but it doesn't work.
This is the submit_job_listing.html template file:
{% extends "base.html" %}
{% load widget_tweaks %}
{% block title %} Submit a job {% endblock %}
{% comment %} https://stackoverflow.com/questions/50028673/changing-active-class-in-bootstrap-navbar-not-staying-in-inherited-django-templa {% endcomment %}
{% block nav_item_post_a_job %}active{% endblock nav_item_post_a_job %}
{% block head %}
{{ job_listing_form.media.css }}
<!---
<style>
input, select {width: 100%}
</style>
--->
{% endblock %}
{% block content %}
{% comment %}
https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html
{% endcomment %}
<h1>Submit a job listing</h1>
<div class="container">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row text-center">
<h2> <b>Job listing information</b> </h2>
</div>
<br />
<div class="row text-center">
<p> <b>Note: Fields marked with an asterisk (*) are required</b> </p>
</div>
<br/>
{% for field in job_listing_form.visible_fields %}
<div class="form-group">
<div class="row">
<p>{{ field.label_tag }}{{ field.field.required|yesno:"*," }}</p>
</div>
<div class="row">
{% if field.help_text %}
<p class="form-text text-muted">{{ field.help_text }}</p>
{% endif %}
</div>
<div class="row">
{{ field }}
<p> {{ field.errors }} </p>
{% if field.errors %}
<div class="border-bottom-danger">
{{ field.errors }}
</div>
{% endif %}
</div>
</div>
{% endfor %}
<br/>
<div class="row text-center">
<h2> <b>Employer information</b> </h2>
</div>
<br />
<div class="row text-center">
<p> <b>Note: Fields marked with an asterisk (*) are required</b> </p>
</div>
<br/>
{% for field in employer_form.visible_fields %}
<div class="form-group">
<div class="row">
<p>{{ field.label_tag }}{{ field.field.required|yesno:"*," }}</p>
</div>
<div class="row">
{% if field.help_text %}
<p class="form-text text-muted">{{ field.help_text }}</p>
{% endif %}
</div>
<div class="row">
{{ field }}
</div>
</div>
{% endfor %}
<input type="submit" value="Submit" class="btn btn-primary" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{{ job_listing_form.media.js }}
</div>
{% endblock %}
When I just click the submit button without inputting anything, all the inputs have a red outline, but nothing gets printed out as field.errors. I don't know why is that. Why is that?
Did you tried debugging in the template ?
I did something like you want to achieve :
<form method="post"> {% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field }}
<label class="control-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
{% if field.errors %}
<div class="border-bottom-danger">
{{ field.errors }}
</div>
{% endif %}
</div>
{% endfor %}
<button class="btn btn-block" type="submit">Submit</button>
</form>
Where :
{{ field }} is the input, where you are correctly adding visible.field.widget.attrs['class'] = 'form-control'
Then, errors you want (I guess) are stored in the field, so you could get its with {{ field.errors }} if it has some.
The difference between your code and mine is that I'm using field.errors instead if field.help_text, I hope it can help.
I suggest you to put breakpoint in your template, then analyze your form object. Then you can do whatever you want in your frontend.
If no error : Add class outline-green to your input wrapper (the <div class="row")
If error : Display the error within a div underneath your input
PS : If you want to outline the input, and not the row wrapper, you can do it through css (or better with Sass if you are using it):
.row.outline-green > input{
border: 1px solid green;
}
<div class="row outline-green">
{{ field }}
</div>
{% load widget_tweaks %}
<div class="col-12 col-md-6">
<div class="form-group">
<label for="{{ form.field1.id_for_label }}" class="text-capitalize">{{ form.field1.label|title }}{% if form.field1.field.required %}<span class="text-danger ml-1">*</span>{% endif %}</label>
{% if form.is_bound %}
{% if form.field1.errors %}
{% render_field form.name class="form-control is-invalid" %}
{% for error in form.field1.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field form.field1 class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field form.field1 class="form-control" %}
{% endif %}
{% if form.field1.help_text %}
<small class="form-text text-muted">{{ form.field1.help_text }}</small>
{% endif %}
</div>
</div>
</div>

Arranging photos in a vertical position in CommerceHQ platform

I'm having some problem with my theme for my e-commerce store. Currently, the product images are aligned in a carousel form. (One large main image, 3-5 thumbnails images below in carousel form)
I'd like to change this to show all photos in same sizes but vertically (top to bottom)
This is my code, how do I change it? I've read stuff online and tried making changes but nothing is happening. Please help.
{{ set(this, 'title', product.seo_title) }}
{% set mainStyles = load.get( loadQuery.cms_items("main-styles", {limit: 50}) ) %}
{% set buttonText = mainStyles[0].settings["Add to cart button text"]|default('Add to Cart') %}
{% set buttonColor = mainStyles[0].settings["Add to cart button color"]|default('inherit') %}
{% set maxRelatedProducts = mainStyles[0].settings["Number of rows for related items"]|default(1) * 3 %}
{% set quanSelector = mainStyles[0].settings["Quantity selector on product page"] %}
{% set imageCrop = mainStyles[0].settings["Product thumbnail aspect ratio"]|default('Smart crop') %}
{% if imageCrop == 'Wide' %}
{% set imageCrop = 'wide' %}
{% elseif imageCrop == 'Tall' %}
{% set imageCrop = 'tall' %}
{% endif %}
<div class="page product" data-productid="{{ product.id }}">
<div class="container">
<div class="col-sm-7">
<div class="fotorama"
data-width="100%"
data-arrows="false"
data-loop="true"
data-autoplay="false"
data-thumbwidth="113"
data-thumbheight="113"
data-thumbborderwidth="4"
data-thumbmargin="5">
{% if product.mainImage %}
<a href="{{ product.mainImage.getImageSize("jumbo") }}">
<img src="{{ product.mainImage.getImageSize("jumbo") }}">
</a>
{% endif %}
</div>
<div class="product-no-image{% if product.mainImage %} hidden{% endif %}">
<img src="/img/icons/image.svg">
</div>
<div class="hidden-xs">
<hr>
{% set relatedProducts = campaign.recommendations({ "product_id": product.id, "limit": maxRelatedProducts }) %}
{% if relatedProducts|length %}
<div class="row related items-grid">
<div class="col-sm-12">
<div class="block-title">
<h3>Related products</h3>
</div>
<div class="items">
{% for product in relatedProducts %}
<div class="col-sm-4 col-xs-6 item {{ imageCrop }}">
<a href="{{ site_path(product.url) }}">
{% if product.mainImage %}
<div class="image"
style="background-image: url('{{ product.mainImage.getImageSize("medium") }}');"></div>
{% else %}
<div class="image empty"></div>
{% endif %}
<p class="title">{{ product.title }}</p>
<p class="price">
{{ product.defaultPrice | currency }}
</p>
</a>
</div>
{% endfor %}
</div>
</div>
</div>
{% endif %}
</div>
</div>
<div class="col-sm-5">
<div class="product-head">
<h2>{{ product.title }}</h2>
<p class="price">
<span id="price">{{ product.price | currency }}</span>
<span class="compare">
<span id="compare-price">{{ product.compare_price | currency(NULL, {"force_prefix_symbol": true}) }}</span>
</span>
</p>
{% if product.variants %}
<div class="variants">
{% for variant in product.allVariants %}
<div class="item">
<span class="label-heading">{{ variant.variant }}</span>
{% if variant.selectorType == "dropdown" %}
<div class="select2">
<select data-variant="{{ loop.index0 }}"
class="product-{{ variant.variant|preg_replace('/[^a-zA-Z0-9]/')|lower }}-select product-select"
title="">
</select>
</div>
{% else %}
<div class="product-colors product-{{ variant.variant|preg_replace('/[^a-zA-Z0-9]/')|lower }}-round">
{% for option in variant.variantOptions %}
<button type="button"
data-variant="{{ loop.parent.loop.index0 }}"
data-option="{{ option.option|preg_replace('/[^a-zA-Z0-9]/')|lower }}"
class="btn-rounded product-color"
style="{% if option.thumbnail.image %}background-image: url('{{ option.thumbnail.imageUrl }}');{% else %}background-color: {{ option.thumbnail.color }}{% endif %}"></button>
{% endfor %}
</div>
{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
{% if quanSelector %}
<div id="quantity-selector" class="quantity">
<span class="label-heading">Quantity</span>
<input type="number">
<button class="down"></button>
<button class="up"></button>
</div>
{% endif %}
{{ system.getApp('ProductCustomizer', {'product_id': product.id} ) }}
<button class="btn" id="buy-it-now"
style="background-color: {{ buttonColor }}">{{ buttonText }}</button>
{{ system.getApp('SecurityBadge', {} ) }}
{{ system.getApp('QuantityLeft', {'product_id': product.id} ) }}
{{ system.getApp('Timer', {'product_id': product.id}) }}
</div>
{% if product.textareaModels %}
<div class="panel-group descriptions" id="accordion" role="tablist" aria-multiselectable="true">
{% for textarea in product.textareaModels %}
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="section-heading{{ loop.index }}">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion"
href="#section{{ loop.index }}"
aria-expanded="{% if loop.index == 1 %}true{% else %}false{% endif %}"
aria-controls="section{{ loop.index }}">
{{ textarea.name|raw }}
<span class="icon__state"></span>
</a>
</h4>
</div>
<div id="section{{ loop.index }}"
class="panel-collapse collapse{% if loop.index == 1 %} in{% endif %}" role="tabpanel"
aria-labelledby="section-heading{{ loop.index }}">
<div class="panel-body">
<div class="typography">{{ textarea.text | raw }}</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endif %}
</div>
<div class="visible-xs">
{% set relatedProducts = campaign.recommendations({ "product_id": product.id, "limit": maxRelatedProducts }) %}
{% if relatedProducts|length %}
<div class="row related items-grid">
<div class="col-sm-12">
<div class="block-title">
<h3>Related products</h3>
</div>
<div class="items">
{% for product in relatedProducts %}
<div class="col-sm-4 col-xs-6 item {{ imageCrop }}">
<a href="{{ site_path(product.url) }}">
{% if product.mainImage %}
<div class="image"
style="background-image: url('{{ product.mainImage.getImageSize("medium") }}');"></div>
{% else %}
<div class="image empty"></div>
{% endif %}
<p class="title">{{ product.title }}</p>
<p class="price">
{{ product.defaultPrice | currency }}
</p>
</a>
</div>
{% endfor %}
</div>
</div>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-sm-12">
{{ system.getApp('Reviews', {'product_id': product.id} ) }}
</div>
</div>
</div>
</div>

grav modular page - separate content and sidebar

I want to create a page in grav, where I have a content area and a sidebar area.
I want to use on modular.md root template in which I refer to a template that loops and displays both content and sidebar modules.
My problem is: how to distinguish between content and sidebar?
my template looks like this:
{% block body %}
{% block content %}
<section id="info">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-8">
<div id="content" class="site-content bg">
<h2 class="heading">{{ page.title }}</h2>
{{ page.content }}
{% for module in page.collection() %}
{{ module.content }}
{% endfor %}
</div>
</div>
<div id="sidebar" class="col-sm-4 sidebar-inner">
{% for module in page.collection() %}
{{ module.content }}
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
{% endblock %}
What I try to achieve is to use filters on both page.collections, so that in one case only "content" (taxonomy.tag was my guess here) and in the other case only sidebar is used.
I could live with naming conventions (sidebar modules have a fixed prefix), but I can't figure it out.
okay, I came along with a hack: I include 'sidebar' in the folder name of the module and filter on module.folder name. I am convinced there is a better solution, though!
<section id="info">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-8">
{% if page.content %}
<div id="content" class="site-content bg">
<h2 class="heading">{{ page.title }}</h2>
{{ page.content }}
</div>
{% endif %}
{% for module in page.collection() %}
{% if 'sidebar' not in module.folder %}
{{ module.content }}
{% endif %}
{% endfor %}
</div>
<div id="sidebar" class="col-sm-4 sidebar-inner">
{% for module in page.collection() %}
{% if 'sidebar' in module.folder %}
{{ module.content }}
{% endif %}
{% endfor %}
</div>
</div>
</div>
</div>
</div>
What you can do (I think) is set a value in the fromtmatter of the module
sidebar: true
Then you can filter on that value in your collection like
{% for module in page.collection() %}
{% if page.header.sidebar %}
{{ module.content }}
{% endif %}
{% endfor %}

How to apply style in data-prototype

I'm trying to apply bootstrap in data-prototype but it is not working.
Below is my twig file
{% block body %}
<div class="container">
<div class="page-header">
<h2>New Company</h2>
</div>
{{ form_start(form) }}
<div class="row">
{{ form_row(form.name) }}
<h3>Employees</h3>
<ul class="employees" data-prototype="{{ form_widget(form.employees.vars.prototype)|e('html_attr') }}">
{% for employee in form.employees %}
<li>
<div class="form-group col-sm-6">
{{ form_row(employee.firstName, {'attr':{'class': 'form-control'}}) }}
</div>
<div class="form-group col-sm-6">
{{ form_row(employee.lastName, {'attr':{'class': 'form-control'}}) }}
</div>
</li>
{% endfor %}
</ul>
<button type="submit" class="btn btn-primary">Save</button>
</div>
{{ form_end(form) }}
</div>
{% endblock %}
Button type is okay but the employee.firstName and employee.lastName are not.
You should create a dedicated form theme for your collection type.
Example:
EmployeeCollectionTypeTheme.html.twig
{% block EmployeeCollectionType_widget %}
<li>
<div class="form-group col-sm-6">
{{ form_row(form.firstName, {'attr':{'class': 'form-control'}}) }}
</div>
<div class="form-group col-sm-6">
{{ form_row(form.lastName, {'attr':{'class': 'form-control'}}) }}
</div>
</li>
{% endblock %}
main.html.twig
{% form_theme form.employees 'AppBundle:Default:EmployeeCollectionTypeTheme.html.twig' %}
<ul class="employees" data-prototype="{{ form_widget(form.employees.vars.prototype)|e('html_attr') }}">
{{ form_widget(form.employees) }}
</ul>
Of course, change form type name to fit with yours (except the form variable in the theme, which is given in the prototype context).
To get further, you can check how I built the collection type for templates in https://twigfiddle.com/ (where you have "Add template" in the left pane), by looking at the theme source code.

How to handle twig view and bootstrap 3 rows/columns?

I have an Article entity and I made a findAll() in the controller.
I rendered each article in a div with the col-md-6 class.
But foreach 2 articles I must wrap these divs in a row div.
How can I do this with twig ?
Thanks.
EDIT :
I tried your code (NHG) like this:
{% for article in articles %}
{% if loop.index % 2 == 0 %}
<div class="row"></div>
{% endif %}
<div class="col-md-6">
<article class="well well-sm">
<img src="{{ article.image }}" alt="{{ article.title }}" class="img-thumbnail">
<h2 class="h3 text-center">{{ article.title }}</h2>
<div class="alert alert-success well-sm">
{{ article.content|striptags|slice(0, 235) }}...
</div>
<a class="btn btn-default btn-sm pull-right" href="#">{{ article.comments|length }} Comments</a>
<div class="btn-group btn-group-sm">
{% for tag in article.tags %}
<a class="btn btn-default">{{ tag.name }}</a>
{% endfor %}
</div>
</article>
</div>
{% endfor %}
But it doesn't work.
I want to have something like this :
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>
UPDATED:
As #Maerlyn suggested:
{% for row in articles|batch(2) %}
<div class="row">
{% for article in row %}
<div class="col-md-6">
// your content
</div>
{% endfor %}
</div>
{% endfor %}
OLD way:
Use loop.index (doc: The loop variable), modulo (doc: Math operators) and if (doc: if statement )
{% for article in articles %}
{% if loop.index % 2 == 1 %}
<div class="row">
{% endif %}
<div class="col-md-6">
// your content
</div>
{% if (loop.index % 2 == 0 or loop.last) %}
</div>
{% endif %}
{% endfor %}
{% for row in articles|batch(2) %}
<div class="row">
{% for article in row %}
<div class="col-md-6">
// your content
{% if loop.index is divisibleby(3) %}
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
I suggest :
<div class="row">
{% for article in articles %}
{% if (loop.index0 % 2 == 0) and not loop.first %}
</div>
<div class="row">
{% endif %}
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
// your content
</div>
{% endfor %}
</div>

Resources