Вывод товара в модальном окне
В этом посте опишу как выводил товар на главной странице в модальном окне.
Сразу хочу сказать, что пост будет чисто для себя как заметка без углубленного объяснения. Если у вас все же будут вопросы по этому посту, то вы можете обратиться комне через форму обратной связи.
На товаре есть кнопка лупы, если по ней нажать откроется модальное окно в котором нужно вывести данные о товаре для быстрого просмотра и заказа.
В общих чертах, что нужно сделать для отображения товара в модальном окне?
1. Сделать вьюху которая будет отвечать за это.
2. Урл на эту вьюху
3. Шаблон где будет выводиться модальное окно
4. Аякс запрос.
Вьюха
def modalproduct(request, slug):
context = {}
modal_product = get_object_or_404(Product, slug=slug)
context['modal_product'] = modal_product
return render(request, 'shop/modal-product.html', context)
Урл
path('modal-product/<slug>/', modalproduct, name='modal-product'),
Шаблон modal-product.html с данными продукта.
{% load staticfiles %}
<div class="product-images">
<div class="main-image images">
<img alt="#" src="{{ modal_product.images.url }}"/>
</div>
</div><!-- .product-images -->
<div class="product-info">
<h1>{{ modal_product.title }}</h1>
<div class="price-box-3">
<hr />
<div class="s-price-box">
<span class="new-price">${{ modal_product.get_sale }}</span>
<span class="old-price">${{ modal_product.price }}</span>
</div>
<hr />
</div>
<a href="{{ modal_product.get_absolute_url }}" class="see-all">See all features</a>
<div class="quick-add-to-cart">
<form class="product-quantity" onsubmit="return addToCart(event)">
<div style="display: inline-block; width: 110px">
<div class="input-group plus-minus-widget">
<span class="input-group-btn">
<button class="btn btn-default" type="button" style="height: 40px; width: 35px" onclick="quantityChange(event, -1)">-</button>
</span>
<input type="text" placeholder="1" value="1" name="quantity" class="form-control" style="height: 40px">
<span class="input-group-btn">
<button class="btn btn-default" type="button" style="height: 40px; width: 35px" onclick="quantityChange(event, +1)">+</button>
</span>
</div>
</div>
<div style="display: inline-block;">
<div class="input-group">
<input type="hidden" name="product" value="{{ modal_product.slug }}"/>
{% if product.stock == 0 %}
{% else %}
<button type="submit" class="toch-button toch-add-cart">Add to Cart</button>
{% endif %}
</div>
</div>
</form>
</div>
<div class="quick-desc">
{{ modal_product.descriptions|truncatewords:25|safe }}
</div>
<div class="social-sharing">
<div class="widget widget_socialsharing_widget">
<h3 class="widget-title-modal">Share this product</h3>
<ul class="social-icons">
<li><a target="_blank" title="Facebook" href="#" class="facebook social-icon"><i class="fa fa-facebook"></i></a></li>
<li><a target="_blank" title="Twitter" href="#" class="twitter social-icon"><i class="fa fa-twitter"></i></a></li>
<li><a target="_blank" title="Pinterest" href="#" class="pinterest social-icon"><i class="fa fa-pinterest"></i></a></li>
<li><a target="_blank" title="Google +" href="#" class="gplus social-icon"><i class="fa fa-google-plus"></i></a></li>
<li><a target="_blank" title="LinkedIn" href="#" class="linkedin social-icon"><i class="fa fa-linkedin"></i></a></li>
</ul>
</div>
</div>
</div><!-- .product-info -->
Кусок кода модального окна в base.html собственно куда и будет подгружаться код из шаблона modal-product.html .
<!-- Modal -->
<div class="modal fade" id="productModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="modal-product jq-product-wrapper"><!--jq-product-wrapper Полет товара в корзину без обновления страницы-->
</div><!-- .modal-product -->
</div><!-- .modal-body -->
</div><!-- .modal-content -->
</div><!-- .modal-dialog -->
</div>
<!-- END Modal -->
Ajax
$('#productModal').on('show.bs.modal', function (event) {
let button = $(event.relatedTarget);
let url = button.data('url');
let container = $(this).find('.modal-product');
container.html('');
$.ajax({
url: url,
}).done(function(data){
container.html(data);
});
});
Код кнопки в шаблоне index.html
<a href="" class="modal-view" data-toggle="modal" data-target="#productModal" data-url="{% url 'shop:modal-product' product.slug %}"><i class="fa fa-search-plus"></i></a>
В общем получился такой разнобой. Попробую все описать более подробней чтоб и самому не забыть)))
С вьюхой, урлом и шаблон modal-product.html тут впринципе все понятно. Во вьюхе получаем продукт по slug и рендерит данные в этот шаблон. В урле так же прокидываем slug.
Далее основное модальное окно находится в шаблоне base.html там есть этот блок див
<div class="modal-product jq-product-wrapper">
</div>
собственно в него и будет подгружаться код из шаблона modal-product.html аякс запросом.
Ну и на главной странице за которую отвечает шаблон index.html там находится кнопка лупы, которая имеет атрибуты для аякс запроса data-target="#productModal" и на вьюху data-url="{% url 'shop:modal-product' product.slug %}"
Впринципе все, если остались вопросы можете писать в комментариях или в форме обратной связи.
Ваши комментарии
Комментарии могут оставлять только зарегистрированые пользователи!