How to get random values with twig including same file multiple times - random

I'm trying to figure out, how to include one template multiple times with different random values.
I do have a template:
<div class="include-1">
{% include 'include.twig' %}
</div>
<div class="include-2">
{% include 'include.twig' %}
</div>
<div class="include-3">
{% include 'include.twig' %}
</div>
Inside the include.twig I have:
<span>
{{ random(10) }}
</span>
Expected result (numbers in span should be random in range from 0–10):
<div class="include-1">
<span>1</span>
</div>
<div class="include-2">
<span>2</span>
</div>
<div class="include-3">
<span>3</span>
</div>
Actual result (the first include get the random value, but then it is just "cached"):
<div class="include-1">
<span>1</span>
</div>
<div class="include-2">
<span>1</span>
</div>
<div class="include-3">
<span>1</span>
</div>
I've tested include, embed etc. but with no avail.
I'm looking for a twig based solution. Cannot touch PHP.
As a fallback I can do it with JS, but was interested if such a thing can be done it Twig.
Question:
Is there a way how to force Twig to re-render the include before each include?

Try passing the random number function as a value on each of your include statements, such as:
<div class="include-1">
{% include 'include.twig' with {'random': random(10) } %}
</div>
Then, inside your include.twig file:
<span>{{ random }}</span>
This will generate the random number for each include you do, and should give you the result you're after.

Related

Is possible to group items according to a front matter variable in Jekyll?

I have a list of cities, each of one contains some stores. I want to loop through each city listing the stores contained in them, and once the loop list all of the stores continues with another city.
Sample html:
<div class="card-group">
<h5 class="heading heading-5">City 1</h5>
<div class="card card-store">
<h6 class="heading heading-6">Store 1</h5>
</div>
<div class="card card-store">
<h6 class="heading heading-6">Store 2</h5>
</div>
</div>
<div class="card-group">
<h5 class="heading heading-5">City 2</h5>
<div class="card card-store">
<h6 class="heading heading-6">Store 3</h5>
</div>
</div>
Currently, I'm setting up a collection with a file for each store with a front matter set like this:
---
title: Store 1
city: City 1
---
I'm trying to figure it out with an if condition the compares the "City" variable. The number of cities is limited, but the stores will grow. I'm not sure if this approach is correct, or if I should create a folder for each city and use something like the "page.collection" variable.
The final project will be deployed in a headless CMS.
Ok, is not the most elegant solution but it works! What I did was:
Create _cities and _stores collections.
Create a "city" front matter variable in the store.
Loop it:
{% for city in site.cities %}
<h5 class="heading heading-5"> {{ city.title }} </h5>
{% for store in site.stores %}
{% if city.title == store.city %}
##DO STUFF
{% endif %}
{% endfor %}
{% endfor %}

Show a collection in laravel from controller on different columns in view

got this problem:
I want to show the info from a collection where a publication has a "featured" column in true.
$pub_destacadas = Publicaciones::take(3)->where('destacado', '=', 1)->get();
The problem is that my layout has 3 elements to fill with this information that have different sizes so i wasn't able to solve this using the chunk() method in the foreach in my blade template, so I tried the following:
$individual_destacada = $pub_destacadas->take(1);
$grupo_destacada = $pub_destacadas->take(2);
and show them in the view as follows:
<div class="publicaciones-destacadas">
<div class="container">
<h2>Publicaciones Destacadas</h2>
<div class="row">
#foreach($individual_destacada as $destacada)
<div class="col-md-6">
<div class="item-destacado size-2">
<img class="img-responsive" src="{{ asset('img/publicaciones/' . $destacada->imagen ) }}">
{{ $destacada->titulo }}
{{ $destacada->descripcion }}
</div>
</div>
#endforeach
<div class="col-md-6">
#foreach($grupo_destacada as $destacada)
<div class="row doble-publicacion">
<div class="col-md-12">
<div class="item-destacado size-1">
<img class="img-responsive" src="{{ asset('img/publicaciones/' . $destacada->imagen ) }}">
{{ $destacada->titulo }}
{{ $destacada->descripcion }}
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
</div>
So... now it shows it correctly in the layout but the first item that the query gets is shown 2 times in this layout. How can I exclude this first element in the second variable where I get the featured publications?
Hope I explained the problem correctly.
Here's the layout:
You can use splice.
$individual_destacada = $pub_destacadas->splice(1);
$grupo_destacada = $pub_destacadas->splice(2);

Rendering images in Twig

I have a form which takes Image (png file type) and saves it's name in the database. The image is uploaded to web/uploads/Images/ directory, my question is, how do I render this image in my Twig template? This is what I have so far:
<div class=products>
{% for key,product in products %}
<div class="product-{{ key }}">
<div class="p-name"> {{ product.name }}</div>
<div class="p-price"> {{ product.price }}</div>
<div class="p-description"> {{ product.description }}</div>
<div class="p-image">
<img src="{{ asset('uploads/Images/' ~ product.Image) }}"></img>
</div>
</div>
{% endfor %}
</div>
And this is what I have in DOM
I am completely new to Symfony, so please bear with me.
EDIT: The path to the image is wrong, how should it be written?
In your img tag you have the spelling of "src" incorrect. Should be like so:
<img src="{{ asset('uploads/Images/' ~ product.Image) }}"></img>
Maybe that's the problem? Otherwise, it looks correct.

Cannot get assign where working in Jekyll template

I have built my website in Jekyll.
The data file is working fine when parsed elsewhere, but when I try to access a particular record using a where clause I get no result.
See the project at https://github.com/ohiweb/ohiweb.github.io
The troublesome page is under portfolio\betimca\index.html
portfolio.yml
projects:
- name: "betimca"
title: "Betimca Subdivision Project"
description: "These beautiful houses in Betimca feature classical elements with modern conveniences. Brick facades are crafted with accents tht stand out for maximum curb appeal. Gables with generous windows allow maximum light to upstairs rooms and add to their distinguished character."
feature: "betimca_1a.jpg"
media: "portfolio/betimca"
images: [betimca_1a.jpg,betimca_1b.jpg,betimca_1c.jpg,betimca_2a.jpg,betimca_2b.jpg,betimca_3a.jpg,betimca_3b.jpg]
tags: ["portfolio", "new construction", "residential", "subdivision"]
index.html
{% assign project = site.data.portfolio.projects | where: "name", "betimca" %}
<section>
<div class="row">
<div class="col col-md-4">
<header class="page-header">
<h1>
{{project.title}}
</h1>
</header>
<p>{{project.description}}</p>
</div>
<div class="col col-md-6 col-md-offset-2">
<img src="/media/{{project.media}}/{{project.feature}}" class="img-responsive img-thumbnail">
</div>
</div>
<hr>
<div class="row">
{% for image in project.images %}
<div class="col col-xs-6 col-sm-4 col-lg-3">
<span class="thumbnail">
<img src="/media/{{project.media}}/{{image}}" alt="{{project.title}} {{image}}">
</span>
</div>
{% endfor %}
</div>
</section>
{% assign project = site.data.portfolio.projects | where: "name", "betimca" %}
This returns an array with one element.
If you want to get the element in project you can do :
{% assign project = site.data.portfolio.projects | where: "name", "betimca" | first %}
And now your page works.

Issues with uploading images to a carousel [duplicate]

This question already has an answer here:
Django template/view issues with carousel
(1 answer)
Closed 7 years ago.
OK, so here's the deal:
This is currently what I'm working on:
See the two arrows at the top? That's where a carousel of pictures should be. However, there are no pictures in this carousel. That is, until I click the 'Upload' Button.
So, my goal is to make the pictures appear on the first page before I even click the 'upload' button.
How can I fix this problem? I'm kind of a noob at Django, and writing this code is like pulling teeth.
My code:
Index.html
{% extends 'webportal/defaults.html' %}
{% block body %}
{% include 'webportal/carousel.html' %}
<br/>
<div class="container">
<div class="row">
<div class="col-md-12">
<p> So far we have been able to establish what the user tables will be have created or are in process of
creating
the ability to create, update, destroy users.</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> For now this ability is limited to the main user table, however the models will be easily extended
to other
tables as they are needed</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> Also not a lot of thought has gone into styling yet, we know that the page is suppose to resemble
the parent
organizations page. Right now we have been more focused on getting each individual component
working. Later we
will merge them into a whole. </p>
</div>
</div>
</div>
{% include 'webportal/info_row.html' with one=one two=two three=three %}
{% endblock %}
Carousel.html:
{% load staticfiles %}
{% load filename %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
{% for document in documents %}
<div class="item {% if forloop.first %} active {% endif %}">
<div class="row">
<div class="col">
<li>{{document.docfile.name}}</li>
<img src = "{{STATIC_URL}}img/{{document|filename}}" >
<p align="center"><form style="text-align:center" action="{% url 'webportal:delete' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.Document.label_tag }} {{ form.Document.help_text }}</p>
<p>
{{ form.Document.errors }}
{{ form.Document.docfile }}
</p>
<p><input type="submit" value="Delete" /></p>
</form></p>
</div>
</div>
</div>
{% endfor %}
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!-- /.carousel -->
</div>
</div>
<form action="{% url 'webportal:carousel' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</div>
Views.py:
from django.shortcuts import render
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login
from webportal.views.authentication import LoginForm
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from webportal.forms.forms import DocumentForm
from webportal.models import Document, DeleteForm
is_server = True
def delete(request, my_id):
Deleted=get_object_or_404(Document, docfile=my_id)
if request.method=='POST':
form=DeleteForm(request.POST, instance=Deleted)
if form.is_valid():
Deleted.delete()
return HttpResponseRedirect('http://127.0.0.1:8000/alzheimers/')
else:
form=DeleteForm(instance=Deleted)
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
# Redirect to the document list after POST
def carousel(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect('http://127.0.0.1:8000/alzheimers/')
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
#documents=DocumentForm().
# Render list page with the documents and the form
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
Models.py:
class Document(models.Model):
docfile = models.ImageField(upload_to='webportal/static/img/')
class DeleteForm(ModelForm):
class Meta:
model=Document
fields=[]
Forms.py:
class DocumentForm(forms.Form):
docfile = forms.ImageField(label='Select a file', help_text='max. 42 megabytes')
URls.py:
from django.conf.urls import patterns, url
from webportal.views import views, register, authentication, welcome, search, profile, event, csv_export, role_creation, \
edit_event, reports, accounts
urlpatterns = patterns('',
url(r'^reports', reports.report_page),
url(r'^search/criteria', search.get_criteria),
url(r'^search', search.search_page),
url(r'^register', register.SignUpView.as_view(), name="register"),
url(r'^login', authentication.login_view, name="login"),
url(r'^carousel', views.carousel, name="carousel"),
url(r'^delete', views.delete, name="delete"),
url(r'^profile', profile.ProfileView.as_view(), name="profile"),
url(r'^welcome', welcome.WelcomeView.as_view(), name="welcome"),
url(r'^event/creation', event.Creation.as_view(), name="event_creation"),
# url(r'^role_creation', role_creation.Creation.as_view(), name="role_creation"),
url(r'^csv_export', csv_export.CSVExport.as_view(), name="csv_export"),
url(r'^csv_import', reports.upload_file, name="csv_import"),
url(r'^logout$', 'django.contrib.auth.views.logout', {'next_page': '/alzheimers/'}),
url(r'^edit_event', edit_event.EditView.as_view(), name='edit_event'),
url(r'^parse_ajax', profile.parse_ajax),
url(r'^event/role_ajax', role_creation.ajax),
url(r'^event/all', event.view_all),
url(r'^event/information', event.ajax),
url(r'^accounts/personal', accounts.personal),
url(r'^accounts/create', accounts.create),
url(r'^accounts/edit', accounts.edit),
url(r'^accounts/remove', accounts.remove),
url(r'^$', views.bootstrap),
)
If there is a way to do this, does it involve ajax? I asked this again because of a lack of an adequate answer.
You should pass the documents context variable to the template in the view which handles the /alzheimers/ page.
UPDATE: The view you should change is the views.boostrap(). So rendering of the template will be something like this:
def bootstrap(request):
...
return render_to_response('webportal/bootstrap.html',
{'documents': Document.objects.all()},
context_instance=RequestContext(request)
)

Resources