I have a Django template with the following code which creates multiple buttons and tries to hide/show description text on a click (on the same button in each card):
{% for comida in comidas %}
{% if comida.slug_food == page.slug %}
<div class="food2">
<div id="food-title">{{comida.titulo}}</div>
<div id="food-price">{{comida.precio|floatformat:"-1"}}€</div>
<button class="button" onclick="showDescription()">ver+
<div id="food-description" >
{{comida.descripcion|safe}}
</div>
</button>
<div id="add-cart">AÑADIR AL PEDIDO</div>
{% if comida.imagen != null %}
<img src="{{comida.imagen.url}}"></img>
{% endif %}
</div>
{% endif %}
{% endfor %}
where comidas is a list of strings, and later in the script block I have
function showDescription(){
var showText = document.getElementById("food-description");
if (showText.style.display === "block"){
showText.style.display = "none";
} else {
showText.style.display = "block";
}
}
The function runs, but as you may expect, it runs only on the first element of my for loop.
My question is ¿anyone can help me? i want work all my buttons and not only the first element.
Use {{comida.id}} to get unique ids :
{% for comida in comidas %}
{% if comida.slug_food == page.slug %}
<div class="food2">
<div id="food-title">{{comida.titulo}}</div>
<div id="food-price">{{comida.precio|floatformat:"-1"}}€</div>
<button class="button" onclick="showDescription('{{comida.id}}')">ver+
<div id="food-description-{{comida.id}}" >
{{comida.descripcion|safe}}
</div>
</button>
<div id="add-cart">AÑADIR AL PEDIDO</div>
{% if comida.imagen != null %}
<img src="{{comida.imagen.url}}"></img>
{% endif %}
</div>
{% endif %}
{% endfor %}
And javascript :
function showDescription(comidaId){
var showText = document.getElementById("food-description-" + comidaId);
if (showText.style.display === "block"){
showText.style.display = "none";
} else {
showText.style.display = "block";
}
}
Related
If the user is not logged in the popup is not interactable but once the user logs in it can be interacted with, not sure why this actually happens and it doesn't seem like it's a JavaScript problem, couldn't find any solutions to it by searching around. I wonder what could cause this behavior on Flask
HTML + Jinja2 :
<body>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
{% if category == "soft-error" %}
<div class="toast" id="toast">
<div class="toast-content">
<div class="close-btn">
<a class="wa-close icon-pos" id="close-btn"></a>
</div>
<div class="message">
<div class="text-content">
<p class="text text-1" id="txt-hide">Error</p>
<span class="text text-2" id="txt-hide-2">{{ message }}</span>
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}{% endblock%}
</body>
JavaScript :
const closeBtn = document.getElementById('close-btn');
const toast = document.getElementById("toast");
closeBtn.addEventListener('click', () => {
toast.parentNode.removeChild(toast);
});
setTimeout(function() {
toast.parentNode.removeChild(toast);
}, 5000);
in my web site i want to show the user ratings for that i used the infinite scroll but i am facing one problem.
when it first loads the data before calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is showing the star with the count of vote,but when after calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is not showing the star.
my views.py
#login_required
def ratings_user(request,pk):
ratings = VoteUser.objects.filter(the_user_id=pk).order_by('-pk')
paginator = Paginator(ratings, 1)
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request,request.session['is_mobile']+'profile/ratings.html',{'ratings':posts})
html
{% extends 'mobile/profile/base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% load get_companion %}
{% load cache %}
{% block title %}
Ratings
{% endblock %}
{% block leftcontent %}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet">
{% endblock %}
{% block middlecontent %}
<div class="infinite-container">
{% for i in ratings %}
<div class="infinite-item">
<div class="w3-container w3-card w3-white w3-round w3-margin">
<img src="{{ i.the_user.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:40px;height:40px;border-radius:50%;">
{% with user=i.the_user.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}
<br>
<span class="stars" data-rating="{{ i.vote.vote }}" data-num-stars="5" ></span>
<hr class="w3-clear">
<p>
{{ i.commentaire|linebreaksbr }}
</p>
<span class="glyphicon glyphicon-user"></span> {% with user=i.the_sender.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}
</div>
</div>
{% endfor %}
</div>
{% if ratings.has_next %}
<a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a>
{% endif %}
{% endblock %}
{% block rightcontent %}
{% endblock %}
{% block js %}
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0]
});
</script>
<script>
//ES5
$.fn.stars = function() {
return $(this).each(function() {
var rating = $(this).data("rating");
var fullStar = new Array(Math.floor(rating + 1)).join('<i class="fas fa-star"></i>');
var halfStar = ((rating%1) !== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
var noStar = new Array(Math.floor($(this).data("numStars") + 1 - rating)).join('<i class="far fa-star"></i>');
$(this).html(fullStar + halfStar + noStar);
});
}
//ES6
$.fn.stars = function() {
return $(this).each(function() {
const rating = $(this).data("rating");
const numStars = $(this).data("numStars");
const fullStar = '<i class="fas fa-star"></i>'.repeat(Math.floor(rating));
const halfStar = (rating%1!== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
const noStar = '<i class="far fa-star"></i>'.repeat(Math.floor(numStars-rating));
$(this).html(`${fullStar}${halfStar}${noStar}`);
});
}
</script>
<script>
$(function(){
$('.stars').stars();
});
</script>
{% endblock %}
i have tried to put the <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"> inside the class="infinite-item" but it does not help.what might be the reason for that ? Thanks.
It doesn't look like .stars() will look for new elements being added to the DOM. You should look for a callback function configuration option within Waypoint.Infinite that you can call .stars() on the new elements.
am using django 2.0 and am trying to make this blog, the issue is that once i click the next page the active bar in the pagination section dont change mean from 1 to 2 see pic image
i don't know where is the mistake
here is the views.py
def post_list(request):
object_list=Post.objects.filter(status='Published').order_by("-created")
pages = pagination(request,object_list,3)
context={
'items':pages[0],
'page_range':pages[1],
}
return render(request,"blog.html",context)
pagination function
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
def pagination(request,data,num=10):
paginator = Paginator(data,num) # Show 5 contacts per page
page = request.GET.get('page',5)
try:
items=paginator.page(page)
except PageNotAnInteger:
items=paginator.page(5)
except EmptyPage:
items=paginator.page(paginator.num_pages)
index=items.number=1
max_index=len(paginator.page_range)
start_index=index - 5 if index >= 5 else 0
end_index=index + 5 if index <= max_index - 5 else max_index
page_range=paginator.page_range[start_index:end_index]
return items, page_range
and pagination.html
<nav>
{% if items.has_other_pages %}
<ul class="pagination">
{% if items.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in page_range %}
{% if items.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if items.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
</ul>
{% endif %}
{% endif %}
</nav>
blog.html
{% for obj in items %}
{% if obj.status == 'Published' %}
<article>
<img src="{{obj.thumb.url}}" alt="" />
<div class="post-content">
<h2>{{obj.title}}</h2>
{{obj.created}} Author {{obj.user}} <h4>{{obj.Category}}</h4>
<hr/>
<p>{{obj.body}}</p>
<a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' obj.slug %}">Continue reading →</a><br>
</div>
</article>
{% endif %}
{% endfor %}
{% include 'pagination.html' %}
</div>
Remove the = 1 from the line index = items.number = 1
I am experimenting with creating a slideshow that has four images, for example. And the thing is I want to create a link button with its own url link for each image. But what I have done is created four link buttons that appears on the slideshow, instead of the one link button that changes along with each image, and with its own url link.
{% if settings.show_block_lookbook %}
<div id="lookbook-section" class="section-full lookbook-section">
<div class="lookbook-wrapper">
<div class="lookbook-text">
<div class="lookbook-container">
<div class="container">
<div class="lb-text">
{% assign lbText1 = settings.block_lookbook_text_1 %}
{% assign lbText2 = settings.block_lookbook_text_2 %}
{% assign lbText3 = settings.block_lookbook_text_3 %}
{% assign lbText4-1 = settings.block_lookbook_text_4_1 %}
{% assign lbText4-2 = settings.block_lookbook_text_4_2 %}
{% assign lbText4-3 = settings.block_lookbook_text_4_3 %}
{% assign lbText4-4 = settings.block_lookbook_text_4_4 %}
{% assign lbLink-1 = settings.block_lookbook_link_1 %}
{% assign lbLink-2 = settings.block_lookbook_link_2 %}
{% assign lbLink-3 = settings.block_lookbook_link_3 %}
{% assign lbLink-4 = settings.block_lookbook_link_4 %}
{% if lbText1 != blank %}<h3>{{ lbText1}}</h3>{% endif %}
<div class="bg-slider-arrows">
<span class="button-prev no-border"></span>
<span class="button-next no-border"></span>
</div>
{% if lbText2 != blank %}<h2>{{ lbText2 }}</h2>{% endif %}
{% if lbText3 != blank %}<p>{{ lbText3 }}</p>{% endif %}
{% if lbText4-1 != blank %}{{ lbText4-1 }}{% endif %}
{% if lbText4-2 != blank %}{{ lbText4-2 }}{% endif %}
{% if lbText4-3 != blank %}{{ lbText4-3 }}{% endif %}
{% if lbText4-4 != blank %}{{ lbText4-4 }}{% endif %}
</div>
</div>
</div>
</div>
</div>
<div class="lookbook-bg">
{% for i in (1..4) %}
{% assign newShow = 'block_lookbook_img_' | append: i %}
{% if settings[newShow] %}
{% assign newImage = 'block_lookbook_img_' | append: i %}
<div class="lookbook-item">
<img src = "{{ newImage | append: '.jpg' | asset_url}}" alt="" />
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
I am totally lost as to what to do, as I am very very new to this. I would think I somehow need to link the images with the urls and link buttons etc, but have no idea how to code it so that each image has its own link button and url link...Any help? Any examples?
Hold on, you are not using much of angular here. I think its django or some other template with {% if %} .
Use something like:
<div ng-repeat="object in objects">
{{object.name }}
<img src="{{ object.img_path}}" />
</div>
For look try this link for ng-repeat
For the functionality u need, I would recommend you to look into cleaner approach of Carousel
I have built a javascript macro and a form theme to render form collections on my website with symfony2.
{{ if prototype is defined }}, I add a 'Add button'.
So far I also have a delete button.
I would like to remove this delete button if 'allow_delete' is not set to true but I can't figure out how to find this in twig.
When I look at my field.vars, there is no allow_delete option. field.vars.attr does not either. How can I do this?
The allow_delete option is a children of you form field.
{% for widget in form.YOURFIELD.children %}
{% if widget.get('allow_delete') %}
//Do your stuff
{% endif %}
{% endfor %}
For those who might be interested, here is my complete solution:
Collections are rendered as tables. Headers are labels or the string
'option' in case of a checkbox.
If the attribute data-label is set in the form, the option is
replaced by the value of data-label.
If allow_add is set to true, an add button is added
if allow_delete is set to true, a delete button is added.
{% block collection_widget %}
{% spaceless %}
<div class="collection">
{% if prototype is defined %}
{% set attr = attr|merge({'data-prototype': block('collection_item_widget') }) %}
{% endif %}
{% if form.vars.allow_delete is defined and form.vars.allow_delete %}
{% set allow_delete = true %}
{% else %}
{% set allow_delete = false %}
{% endif %}
<div {{ block('widget_container_attributes') }} class="protoype">
{% if prototype is defined %}
Ajouter <i class="fa fa-plus"></i>
{% endif %}
{{ form_errors(form) }}
<table class="subtable table">
<thead>
<tr class="headers" style="display: none;">
{% if form.children|length > 0 %}
{% if form.children[0]|length > 0 %}
{% set header = form.children[0] %}
{{ block('collection_header') }}
{% endif %}
{% endif %}
</tr>
</thead>
<tbody class="container_rows">
{% for rows in form %}
{% spaceless %}
{% if rows.children|length > 0 %}
<tr class="row_to_delete child_collection">
{% set body = rows %}
{{ block('collection_body') }}
</tr>
{% endif %}
{% endspaceless %}
{% endfor %}
</tbody>
</table>
{#{{ form_rest(form) }}#}
</div>
</div>
{% endspaceless %}
{% endblock collection_widget %}
{% block collection_item_widget %}
{% set header = prototype %}
{% set body = prototype %}
{% spaceless %}
{{ block('collection_body') }}
{% endspaceless %}
{% endblock collection_item_widget %}
{% block collection_header %}
{% for field in header %}
<th>
{% if 'checkbox' not in field.vars.block_prefixes %}
{{ form_label(field)|raw }}
{% else %}
{% if field.vars.attr['data-label'] is defined %}
{{ field.vars.attr['data-label'] }}
{% else %}
Options
{% endif %}
{% endif %}
</th>
{% endfor %}
{% if allow_delete %}
<th class="fmu_table_center">Supprimer</th>
{% endif %}
{% endblock %}
{% block collection_body %}
{% set fieldNum = 1 %}
{% for field in body %}
<td class="field{{ fieldNum }} data-label">
{% if field.vars.attr['class'] is defined %}
{% set class = field.vars.attr['class'] ~ ' input-sm' %}
{% else %}
{% set class = 'input-sm' %}
{% endif %}
{% set attr = field.vars.attr|merge({'class': class }) %}
{{ form_widget(field, {'attr' : attr}) }}
{{ form_errors(field) }}
</td>
{% set fieldNum = fieldNum + 1 %}
{% endfor %}
{% if allow_delete %}
<td class="fmu_table_center fmu_table_middle"><i class="fa fa-times"></i></td>
{% endif %}
{% endblock %}
and my javascript :
{% macro javascript_form_collection() %}
{#ass the necessary javascript to handle a collection#}
<script>
$(function() {
$('.collection').each(function(){
var $container = $(this).children('div:first-child');
var $addButton = $container.children('.add_button').eq(0);
$addButton.on('click', function(e) {
addElement($container,index);
count++;
index++;
showHeaders($container, count);
e.preventDefault();
return false;
});
var count = $container.find('.child_collection').length;
var index = $container.find('.child_collection').length;
if (count == 0)
{
populateHeaders($container)
}
$container.on('click','.fmu_delete_button', function(e){
e.preventDefault();
var $row = $(this).closest('.row_to_delete');
$row.next('.sibling_row_to_delete').remove();
$row.next('.sibling_row_to_delete_2').remove();
$row.remove();
count--;
showHeaders($container, count);
});
showHeaders($container, count);
});
function populateHeaders($container)
{
var $headers = $container.find('.headers').eq(0);
var $prototype = $($container.attr('data-prototype'));
var $headerPrototype = $($prototype[0]).attr('data-label');
$headers.html($headerPrototype);
}
function showHeaders($container, count)
{
if (count > 0)
{
$container.find('.subtable .headers').show();
}
else
{
$container.find('.subtable .headers').hide();
}
}
function addElement($container, index) {
var $prototype = $($container.attr('data-prototype')
.replace(/__name__label__/g, 'n°' + (index+1))
.replace(/__name__/g, index));
$container.find('.container_rows').eq(0).append($prototype);
$('.timepicker').timepicker();
$('.datetimepicker').datetimepicker();
$prototype.find('.select2').each(function(){
$(this).select2();
});
$('[data-toggle="tooltip"]').tooltip();
return $prototype;
}
});
</script>
<style type="text/css">
.subtable {
width: 100%;
}
.subtable th {
font-weight: normal;
}
</style>
{% endmacro %}