Перейти к содержанию
Официальный форум поддержки Simpla

Вывести рекомендуемые товары в шаблоне products.tpl


Рекомендуемые сообщения

Как можно вывести рекомендуемые товары через шаблон products.tpl, Делаю в нем

{if $smarty.server.REQUEST_URI == "/products"}
<div id="catalog_recommend">
{include file="catalog_tree.tpl"}
{get_featured_products var=featured_products}
<!--Каталог товаров-->
{if $featured_products}
<!-- Список товаров-->
<div id="catalog_right">
        <ul>
        {foreach $products as $product}
	<!-- Товар-->
	<li class="product procart">
		<!-- Фото товара -->
		{if $product->image}
                <div class="imacart ima_hover">
                 <img src="{$product->image->filename|resize:165:165}" alt="{$product->name|escape}"></div>
         	{/if}
                <div class="infoproduct">
		<!-- Название товара -->
		<h3>{$product->name|escape}</h3>
		<!-- Название товара (The End) -->
		<!-- Выбор варианта товара -->
			{foreach $product->variants as $v}
           <span class="price">{$v->price|convert} {$currency->sign|escape}</span>
			{/foreach}
                        <div class="info_small">
           <form class="variants" action="/cart">
			<input style="display:none"  id="variants_{$v->id}" name="variant" value="{$v->id}" type="radio"checked /> 
			<input type="submit" value="В корзину" data-result-text="Добавлено" class="cart_var"/>
                        <input type="button" value="Подробнее" onclick="location.href='products/{$product->url}'" class="more_var"/>
                 </form></div></div>
         </li>
         {/foreach}
         </ul>
         <div class="pag">
             {include file='pagination.tpl'}
         </div>
<!-- Заголовок страницы -->
<h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
</div>
</div>
{else}
 <div class="page_false">
 <h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
 <p>В данной категории нет товаров</p>
 </div>
 {/if}
<!-- Выбор варианта товара (The End) -->

При заходе на страницу выдается ошибка сервера.

Вот полный код products.tpl:

{if $smarty.server.REQUEST_URI == "/products"}
<div id="catalog_recommend">
{include file="catalog_tree.tpl"}
{get_featured_products var=featured_products}
<!--Каталог товаров-->
{if $featured_products}
<!-- Список товаров-->
<div id="catalog_right">
        <ul>
        {foreach $products as $product}
	<!-- Товар-->
	<li class="product procart">
		<!-- Фото товара -->
		{if $product->image}
                <div class="imacart ima_hover">
                 <img src="{$product->image->filename|resize:165:165}" alt="{$product->name|escape}"></div>
         	{/if}
                <div class="infoproduct">
		<!-- Название товара -->
		<h3>{$product->name|escape}</h3>
		<!-- Название товара (The End) -->
		<!-- Выбор варианта товара -->
			{foreach $product->variants as $v}
           <span class="price">{$v->price|convert} {$currency->sign|escape}</span>
			{/foreach}
                        <div class="info_small">
           <form class="variants" action="/cart">
			<input style="display:none"  id="variants_{$v->id}" name="variant" value="{$v->id}" type="radio"checked /> 
			<input type="submit" value="В корзину" data-result-text="Добавлено" class="cart_var"/>
                        <input type="button" value="Подробнее" onclick="location.href='products/{$product->url}'" class="more_var"/>
                 </form></div></div>
         </li>
         {/foreach}
         </ul>
         <div class="pag">
             {include file='pagination.tpl'}
         </div>
<!-- Заголовок страницы -->
<h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
</div>
</div>
{else}
 <div class="page_false">
 <h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
 <p>В данной категории нет товаров</p>
 </div>
 {/if}
<!-- Выбор варианта товара (The End) -->
<!-- Хлебные крошки /-->
<div id="path">
	<a href="/">Главная</a>
	{if $category}
	{foreach from=$category->path item=cat}
	? <a class="selected" href="catalog/{$cat->url}">{$cat->name|escape}</a>
	{/foreach}  
	{if $brand}
	? <a class="selected" href="catalog/{$cat->url}/{$brand->url}">{$brand->name|escape}</a>
	{/if}
	{elseif $brand}
	? <a class="selected" href="brands/{$brand->url}">{$brand->name|escape}</a>
	{elseif $keyword}
	? Поиск
	{/if}
</div>
{if $products}
<h1>{$brand->name|escape}</h1>
{$brand->description}
<div id="catalog_recommend">
{include file="catalog_tree.tpl"}
<!--Каталог товаров-->
<!-- Список товаров-->
<div id="catalog_right">
 <div id="catalog_filter">
 {* Фильтр по брендам *}
{if $category->brands}
  <div class="brands">Брэнды<div class="brand_img"></div>
<ul class="brand_1">
<li><a href="catalog/{$category->url}" {if !$brand->id}class="selected"{/if}>Все брэнды</a></li>
	{foreach name=brands item=b from=$category->brands}
<li><a data-brand="{$b->id}" href="catalog/{$category->url}/{$b->url}" 
{if $b->id == $brand->id}class="selected"{/if}>{$b->name|escape}</a></li>
	{/foreach}
</ul>
</div>
{/if}
<!--Фильтр по свойствам-->
{if $features}
<table id="features">
	{foreach $features as $f}
	<tr>
	<td class="feature_name" data-feature="{$f->id}">
		{$f->name}:
	</td>
	<td class="feature_values">
		<a href="{url params=[$f->id=>null, page=>null]}" {if !$smarty.get.$f@key}class="selected"{/if}>Все</a>
		{foreach $f->options as $o}
		<a href="{url params=[$f->id=>$o->value, page=>null]}" {if $smarty.get.$f@key == $o->value}class="selected"{/if}>{$o->value|escape}</a>
		{/foreach}
	</td>
	</tr>
	{/foreach}
</table>
{/if}
 </div>
         <ul>
                 {foreach $products as $product}
	<!-- Товар-->
	<li class="product procart">
		<!-- Фото товара -->
		{if $product->image}
                <div class="imacart ima_hover">
                 <img src="{$product->image->filename|resize:165:165}" alt="{$product->name|escape}"></div>
         	{/if}
                <div class="infoproduct">
		<!-- Название товара -->
		<h3>{$product->name|escape}</h3>
		<!-- Название товара (The End) -->
		<!-- Выбор варианта товара -->
			{foreach $product->variants as $v}
	   <span class="price">{$v->price|convert} {$currency->sign|escape}</span>
			{/foreach}
                        <div class="info_small">
<form class="variants" action="/cart">
			<input style="display:none"  id="variants_{$v->id}" name="variant" value="{$v->id}" type="radio"checked> 
			<input type="submit" value="В корзину" data-result-text="Добавлено" class="cart_var"/>
                        <input type="button" value="Подробнее" onclick="location.href='products/{$product->url}'" class="more_var"/>
                         </form></div>
         </div>
         </li>
          {/foreach}
</ul>
          <div class="pag">
          {include file='pagination.tpl'}
          </div>
</div>
{else}
 <p>В данной категории нет товаров</p>
{/if}
 </div>
 </div>

 

 

В чем может быть проблема, заранее благодарен за любую помощь.

Ссылка на сообщение
Поделиться на другие сайты

Во-первых, что за ошибка? В какой строке? Текст ошибки?

Все эти данные доступны на локалке и правильно настроенном сервере.

Лично я без этих данных вам ответить не готов, если найдется кто-то, настолько не уважающий себя - то вам повезет))

Ссылка на сообщение
Поделиться на другие сайты

напишите что вы именно хотите, без вашего кода. возможно ответ окажется банально простым.

Ссылка на сообщение
Поделиться на другие сайты

У меня новинки, товары по акции,рекомендуемые формируются через шаблон page.tpl, через 

{if $smarty.server.REQUEST_URI == "/products"}

 

но насколько я понимаю настраивать таким образом пагинацию необдуманное решение. На шаблоне products.tpl пагинация есть и я хочу через него вывести страницы рекомендуемые, новинки, лови момент. Но когда я в шаблон products.tpl вставляю код, я получаю http://choosemood.ru/products вот мой код products.tpl со вставленным кодом рекомендуемых:

{if $smarty.server.REQUEST_URI == "/products"}
<div id="catalog_recommend">
{include file="catalog_tree.tpl"}
{get_featured_products var=featured_products}
<!--Каталог товаров-->
{if $featured_products}
<!-- Список товаров-->
<div id="catalog_right">
        <ul>
        {foreach $products as $product}
	<!-- Товар-->
	<li class="product procart">
		<!-- Фото товара -->
		{if $product->image}
                <div class="imacart ima_hover">
                 <img src="{$product->image->filename|resize:165:165}" alt="{$product->name|escape}"></div>
         	{/if}
                <div class="infoproduct">
		<!-- Название товара -->
		<h3>{$product->name|escape}</h3>
		<!-- Название товара (The End) -->
		<!-- Выбор варианта товара -->
			{foreach $product->variants as $v}
           <span class="price">{$v->price|convert} {$currency->sign|escape}</span>
			{/foreach}
                        <div class="info_small">
           <form class="variants" action="/cart">
			<input style="display:none"  id="variants_{$v->id}" name="variant" value="{$v->id}" type="radio"checked /> 
			<input type="submit" value="В корзину" data-result-text="Добавлено" class="cart_var"/>
                        <input type="button" value="Подробнее" onclick="location.href='products/{$product->url}'" class="more_var"/>
                 </form></div></div>
         </li>
         {/foreach}
         </ul>
         <div class="pag">
             {include file='pagination.tpl'}
         </div>
<!-- Заголовок страницы -->
<h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
</div>
</div>
{else}
 <div class="page_false">
 <h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
 <p>В данной категории нет товаров</p>
 </div>
 {/if}
<!-- Выбор варианта товара (The End) -->
<!-- Хлебные крошки /-->
<div id="path">
	<a href="/">Главная</a>
	{if $category}
	{foreach from=$category->path item=cat}
	? <a class="selected" href="catalog/{$cat->url}">{$cat->name|escape}</a>
	{/foreach}  
	{if $brand}
	? <a class="selected" href="catalog/{$cat->url}/{$brand->url}">{$brand->name|escape}</a>
	{/if}
	{elseif $brand}
	? <a class="selected" href="brands/{$brand->url}">{$brand->name|escape}</a>
	{elseif $keyword}
	? Поиск
	{/if}
</div>
{if $products}
<h1>{$brand->name|escape}</h1>
{$brand->description}
<div id="catalog_recommend">
{include file="catalog_tree.tpl"}
<!--Каталог товаров-->
<!-- Список товаров-->
<div id="catalog_right">
 <div id="catalog_filter">
 {* Фильтр по брендам *}
{if $category->brands}
  <div class="brands">Брэнды<div class="brand_img"></div>
<ul class="brand_1">
<li><a href="catalog/{$category->url}" {if !$brand->id}class="selected"{/if}>Все брэнды</a></li>
	{foreach name=brands item=b from=$category->brands}
<li><a data-brand="{$b->id}" href="catalog/{$category->url}/{$b->url}" 
{if $b->id == $brand->id}class="selected"{/if}>{$b->name|escape}</a></li>
	{/foreach}
</ul>
</div>
{/if}
<!--Фильтр по свойствам-->
{if $features}
<table id="features">
	{foreach $features as $f}
	<tr>
	<td class="feature_name" data-feature="{$f->id}">
		{$f->name}:
	</td>
	<td class="feature_values">
		<a href="{url params=[$f->id=>null, page=>null]}" {if !$smarty.get.$f@key}class="selected"{/if}>Все</a>
		{foreach $f->options as $o}
		<a href="{url params=[$f->id=>$o->value, page=>null]}" {if $smarty.get.$f@key == $o->value}class="selected"{/if}>{$o->value|escape}</a>
		{/foreach}
	</td>
	</tr>
	{/foreach}
</table>
{/if}
 </div>
         <ul>
                 {foreach $products as $product}
	<!-- Товар-->
	<li class="product procart">
		<!-- Фото товара -->
		{if $product->image}
                <div class="imacart ima_hover">
                 <img src="{$product->image->filename|resize:165:165}" alt="{$product->name|escape}"></div>
         	{/if}
                <div class="infoproduct">
		<!-- Название товара -->
		<h3>{$product->name|escape}</h3>
		<!-- Название товара (The End) -->
		<!-- Выбор варианта товара -->
			{foreach $product->variants as $v}
	   <span class="price">{$v->price|convert} {$currency->sign|escape}</span>
			{/foreach}
                        <div class="info_small">
<form class="variants" action="/cart">
			<input style="display:none"  id="variants_{$v->id}" name="variant" value="{$v->id}" type="radio"checked> 
			<input type="submit" value="В корзину" data-result-text="Добавлено" class="cart_var"/>
                        <input type="button" value="Подробнее" onclick="location.href='products/{$product->url}'" class="more_var"/>
                         </form></div>
         </div>
         </li>
          {/foreach}
</ul>
          <div class="pag">
          {include file='pagination.tpl'}
          </div>
</div>
{else}
 <p>В данной категории нет товаров</p>
{/if}
 </div>
 </div>

 


 

Ссылка на сообщение
Поделиться на другие сайты

Примерно так:

.htaccess

RewriteRule ^hits/?$ index.php?module=ProductsView&mode=hits [L,QSA]

ProductsView.php

$mode = $this->request->get('mode', 'string');

 

if ($mode == 'hits')

{

$filter['featured'] = 1;

}

Аналогично в 3-4 строки делается вывод Новинок (надо поставить лимит, а то все товары выведутся) и Акционных.

С пагинацией, мета-тегами и прочей фигней.

Ссылка на сообщение
Поделиться на другие сайты

Блин, НИЧЕГО НИГДЕ не надо создавать, все работает БЕЗ лищних файлов и т.д.

Один файл Вью работает, ProductsView.php, ВСЕ работает из ЭТОГО файла...

НИКАКИХ дополнительных файлов НЕ НАДО.

Ссылка на сообщение
Поделиться на другие сайты

В моем варианте делаете правки, потом создаете СТРАНИЦУ с адресом hits

На ней выводятся ВСЕ рекомендуемые, с пагинацией и т.д.

Ссылка на сообщение
Поделиться на другие сайты

Я не до конца понял.

1.RewriteRule ^hits/?$ index.php?module=ProductsView&mode=hits [L,QSA] добавил в корневой .htaccess.

2. hits - заменил на интерисующую меня страницу.

3. во view/productsview.php -  в самое начало добавил код:

$mode = $this->request->get('mode', 'string');

if ($mode == 'hits')
{
$filter['featured'] = 1;
}

hits - адрес моей страницы.(/novinki)

У меня изначально страница выводилась через page.tpl, если я конструкцию вывода новинок копирую в products.tpl то ничего не работает:

{if $smarty.server.REQUEST_URI == "/novinki"}
<h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
<!--Каталог товаров-->
<div id="catalog_spec">
{get_new_products var=new_products}
{if $new_products}
<!-- Список товаров-->
        <ul>
        {foreach $new_products as $product}
	<!-- Товар-->
<li class="product procart">
		<!-- Фото товара -->
		{if $product->image}
                <div class="imacart">
                 <img src="{$product->image->filename|resize:165:165}" alt="{$product->name|escape}"></div>
                 {/if}
                <div class="infoproduct">
		<!-- Название товара -->
		<h3>{$product->name|escape}</h3>
		<!-- Название товара (The End) -->
		<!-- Выбор варианта товара -->
			{foreach $product->variants as $v}
	   <span class="price">{$v->price|convert} {$currency->sign|escape}</span>
			{/foreach}
                        <div class="info_small">
<form class="variants" action="/cart">
			<input style="display:none"  id="variants_{$v->id}" name="variant" value="{$v->id}" type="radio"checked> 
			<input type="submit" value="В корзину" data-result-text="Добавлено" class="cart_var"/>
                        <input type="button" value="Подробнее" onclick="location.href='products/{$product->url}'" class="more_var"/>
                 </form></div>
		<!-- Выбор варианта товара (The End) -->
         </div>
		<!-- Фото товара (The End) -->
</li>
<!-- Товар (The End)-->   
{/foreach}
</ul>
 {/if}
</div>
{include file='pagination.tpl'}
Ссылка на сообщение
Поделиться на другие сайты

А зачем что-то куда-то копировать?

Лучше выложите строки из ВАШИХ файлов, кто его знает, что там написано...

Ссылка на сообщение
Поделиться на другие сайты

Файл .htaccess в корне сайта:

AddDefaultCharset UTF-8
ErrorDocument 404 /404
ErrorDocument 401 /password.php
RewriteEngine on

# Админка теперь по адресу /simpla
RewriteRule	^admin/?$  simpla [L]


# Каталог товаров
RewriteRule ^catalog/([^/]+)/?$	index.php?module=ProductsView&category=$1 [L,QSA]
RewriteRule ^catalog/([^/]+)/([^/]+)/?$	index.php?module=ProductsView&category=$1&brand=$2 [L,QSA]

RewriteRule ^products/([^/]+)/?$	index.php?module=ProductView&product_url=$1 [L,QSA]
RewriteRule ^products/?$	index.php?module=ProductsView [L,QSA]

RewriteRule ^brands/([^/]+)/?$	index.php?module=ProductsView&brand=$1 [L,QSA]
RewriteRule ^brands/([^/]+)/page_([^/]+)/?$	index.php?module=ProductsView&brand=$1&page=$2 [L,QSA]

# Поиск товаров
RewriteRule ^search/([^/]+)/?$	index.php?module=ProductsView&keyword=$1 [L,QSA]
RewriteRule ^search/?$	index.php?module=ProductsView [L,QSA]

# Блог
RewriteRule ^blog/([^/]+)/?$	index.php?module=BlogView&url=$1 [L,QSA]
RewriteRule ^blog/?$	index.php?module=BlogView [L,QSA]

# Корзина и заказы
RewriteRule ^cart/?$	index.php?module=CartView   [L,QSA]
RewriteRule ^cart/([^/]+)/?$	index.php?module=CartView&add_variant=$1  [L,QSA]
RewriteRule ^cart/remove/([^/]+)/?$	index.php?module=CartView&delete_variant=$1  [L,QSA]
RewriteRule ^order/([^/]+)/?$	index.php?module=OrderView&url=$1  [L,QSA]
RewriteRule ^order/?$	index.php?module=OrderView  [L,QSA]

# Для пользователей
RewriteRule ^user/login/?$	index.php?module=LoginView  [L,QSA]
RewriteRule ^user/register/?$	index.php?module=RegisterView  [L,QSA]
RewriteRule ^user/logout/?$	index.php?module=LoginView&action=logout  [L,QSA]
RewriteRule ^user/password_remind/?$	index.php?module=LoginView&action=password_remind  [L,QSA]
RewriteRule ^user/password_remind/([0-9a-z]+)/?$	index.php?module=LoginView&action=password_remind&code=$1  [L,QSA]
RewriteRule ^user/?$	index.php?module=UserView  [L,QSA]

# Google sitemap
RewriteRule ^sitemap.xml?$	sitemap.php  [L,QSA]

# XML
RewriteRule ^yandex.xml?$	yandex.php  [L,QSA]

# feedback
RewriteRule ^contact/?$	index.php?module=FeedbackView  [L,QSA]

#downloads
RewriteRule ^order/([^/]+)/([^/]+)/?$	index.php?module=OrderView&url=$1&file=$2  [L,QSA]


# Статические страницы
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/?$	index.php?module=PageView&page_url=$1 [L,QSA]
RewriteRule ^/?$	index.php?module=MainView&page_url= [L,QSA]

# Ресайз картинок на лету
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^files/products/(.+) resize/resize.php?file=$1&token=%{QUERY_STRING}
#RewriteCond %{THE_REQUEST} ^GET\ (.*)files/products/(.*)\?([A-z0-9]*) 
#RewriteRule ^files/products/(.+) resize/resize.php?file=%2&token=%3 [L,NE]

#Добавление
RewriteRule ^novinki/?$ index.php?module=ProductsView&mode=novinki [L,QSA]

Файл productsview.php в самое начало добавил:

<?PHP

/**
 * Simpla CMS
 *
 * @copyright 	2011 Denis Pikusov
 * @link 		http://simplacms.ru
 * @author 		Denis Pikusov
 *
 * Этот класс использует шаблон products.tpl
 *
 */
$mode = $this->request->get('mode', 'string');

if ($mode == 'novinki')
{
$filter['featured'] = 1;
}
require_once('View.php');

class ProductsView extends View
{
 	/**
	 *
	 * Отображение списка товаров
	 *
	 */	
	function fetch()
	{
		// GET-Параметры
		$category_url = $this->request->get('category', 'string');
		$brand_url    = $this->request->get('brand', 'string');
		
		$filter = array();
		$filter['visible'] = 1;	

		// Если задан бренд, выберем его из базы
		if (!empty($brand_url))
		{
			$brand = $this->brands->get_brand((string)$brand_url);
			if (empty($brand))
				return false;
			$this->design->assign('brand', $brand);
			$filter['brand_id'] = $brand->id;
		}
		
		// Выберем текущую категорию
		if (!empty($category_url))
		{
			$category = $this->categories->get_category((string)$category_url);
			if (empty($category) || (!$category->visible && empty($_SESSION['admin'])))
				return false;
			$this->design->assign('category', $category);
			$filter['category_id'] = $category->children;
		}

		// Если задано ключевое слово
		$keyword = $this->request->get('keyword');
		if (!empty($keyword))
		{
			$this->design->assign('keyword', $keyword);
			$filter['keyword'] = $keyword;
		}

		// Сортировка товаров, сохраняем в сесси, чтобы текущая сортировка оставалась для всего сайта
		if($sort = $this->request->get('sort', 'string'))
			$_SESSION['sort'] = $sort;		
		if (!empty($_SESSION['sort']))
			$filter['sort'] = $_SESSION['sort'];			
		else
			$filter['sort'] = 'position';			
		$this->design->assign('sort', $filter['sort']);
		
		// Свойства товаров
		if(!empty($category))
		{
			$features = array();
			foreach($this->features->get_features(array('category_id'=>$category->id, 'in_filter'=>1)) as $feature)
			{ 
				$features[$feature->id] = $feature;
				if(($val = strval($this->request->get($feature->id)))!='')
					$filter['features'][$feature->id] = $val;	
			}
			
			$options_filter['visible'] = 1;
			
			$features_ids = array_keys($features);
			if(!empty($features_ids))
				$options_filter['feature_id'] = $features_ids;
			$options_filter['category_id'] = $category->children;
			if(isset($filter['features']))
				$options_filter['features'] = $filter['features'];
			if(!empty($brand))
				$options_filter['brand_id'] = $brand->id;
			
			$options = $this->features->get_options($options_filter);

			foreach($options as $option)
			{
				if(isset($features[$option->feature_id]))
					$features[$option->feature_id]->options[] = $option;
			}
			
			foreach($features as $i=>&$feature)
			{ 
				if(empty($feature->options))
					unset($features[$i]);
			}

			$this->design->assign('features', $features);
 		}
		// Постраничная навигация
		$items_per_page = $this->settings->products_num;		
		// Текущая страница в постраничном выводе
		$current_page = $this->request->get('page', 'int');	
		// Если не задана, то равна 1
		$current_page = max(1, $current_page);
		$this->design->assign('current_page_num', $current_page);
		// Вычисляем количество страниц
		$products_count = $this->products->count_products($filter);
		
		// Показать все страницы сразу
		if($this->request->get('page') == 'all')
			$items_per_page = $products_count;	
		
		$pages_num = ceil($products_count/$items_per_page);
		$this->design->assign('total_pages_num', $pages_num);

		$filter['page'] = $current_page;
		$filter['limit'] = $items_per_page;
		
		///////////////////////////////////////////////
		// Постраничная навигация END
		///////////////////////////////////////////////
		
		
		
		
		$discount = 0;
		if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id'])))
			$discount = $user->discount;
			
		// Товары 
		$products = array();
		foreach($this->products->get_products($filter) as $p)
			$products[$p->id] = $p;
			
		// Если искали товар и найден ровно один - перенаправляем на него
		if(!empty($keyword) && $products_count == 1)
			header('Location: '.$this->config->root_url.'/products/'.$p->url);
		
		if(!empty($products))
		{
			$products_ids = array_keys($products);
			foreach($products as &$product)
			{
				$product->variants = array();
				$product->images = array();
				$product->properties = array();
			}
	
			$variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true));
			
			foreach($variants as &$variant)
			{
				//$variant->price *= (100-$discount)/100;
				$products[$variant->product_id]->variants[] = $variant;
			}
	
			$images = $this->products->get_images(array('product_id'=>$products_ids));
			foreach($images as $image)
				$products[$image->product_id]->images[] = $image;

			foreach($products as &$product)
			{
				if(isset($product->variants[0]))
					$product->variant = $product->variants[0];
				if(isset($product->images[0]))
					$product->image = $product->images[0];
			}
				
	
			/*
			$properties = $this->features->get_options(array('product_id'=>$products_ids));
			foreach($properties as $property)
				$products[$property->product_id]->options[] = $property;
			*/
	
			$this->design->assign('products', $products);
 		}
		
		// Выбираем бренды, они нужны нам в шаблоне	
		if(!empty($category))
		{
			$brands = $this->brands->get_brands(array('category_id'=>$category->children));
			$category->brands = $brands;		
		}
		
		// Устанавливаем мета-теги в зависимости от запроса
		if($this->page)
		{
			$this->design->assign('meta_title', $this->page->meta_title);
			$this->design->assign('meta_keywords', $this->page->meta_keywords);
			$this->design->assign('meta_description', $this->page->meta_description);
		}
		elseif(isset($category))
		{
			$this->design->assign('meta_title', $category->meta_title);
			$this->design->assign('meta_keywords', $category->meta_keywords);
			$this->design->assign('meta_description', $category->meta_description);
		}
		elseif(isset($brand))
		{
			$this->design->assign('meta_title', $brand->meta_title);
			$this->design->assign('meta_keywords', $brand->meta_keywords);
			$this->design->assign('meta_description', $brand->meta_description);
		}
		elseif(isset($keyword))
		{
			$this->design->assign('meta_title', $keyword);
		}
		
			
		$this->body = $this->design->fetch('products.tpl');
		return $this->body;
	}
	
	

}

У меня в шаблоне page.tpl идет вывод через if smarty server:

{elseif $smarty.server.REQUEST_URI == "/novinki"}
<!-- Заголовок страницы -->
<h1 class="h1_zag" data-page="{$page->id}">{$page->header|escape}</h1>
<!-- Тело страницы -->
{$page->body}
<!--Каталог товаров-->
<div id="catalog_spec">
{get_new_products var=new_products}
{if $new_products}
<!-- Список товаров-->
        <ul>
        {foreach $new_products as $product}
	<!-- Товар-->
<li class="product procart">
		<!-- Фото товара -->
		{if $product->image}
                <div class="imacart ima_hover">
                 <img src="{$product->image->filename|resize:165:165}" alt="{$product->name|escape}"></div>
                 {/if}
                <div class="infoproduct">
		<!-- Название товара -->
		<h3>{$product->name|escape}</h3>
		<!-- Название товара (The End) -->
		<!-- Выбор варианта товара -->
			{foreach $product->variants as $v}
	   <span class="price">{$v->price|convert} {$currency->sign|escape}</span>
			{/foreach}
                        <div class="info_small">
                       <form class="variants" action="/cart">
			<input style="display:none"  id="variants_{$v->id}" name="variant" value="{$v->id}" type="radio"checked> 
			<input type="submit" value="В корзину" data-result-text="Добавлено" class="cart_var"/>
                        <input type="button" value="Подробнее" onclick="location.href='products/{$product->url}'" class="more_var"/>
                 </form></div>

		<!-- Выбор варианта товара (The End) -->
         </div>
		<!-- Фото товара (The End) -->
</li>
<!-- Товар (The End)-->   
{/foreach}
</ul>
 {/if}
</div>
{include file='pagination.tpl'}

Что нужно поменять, чтобы пагинация заработала. Страница с новинками http://choosemood.ru/novinki сейчас насколько я понимаю вывод идет через if smarty server... Заранее благодарен за любую помощь.

Ссылка на сообщение
Поделиться на другие сайты

#Добавление

RewriteRule ^novinki/?$ index.php?module=ProductsView&mode=novinki [L,QSA]

Вот это - в НАЧАЛО файла, сразу после админки.

$mode = $this->request->get('mode', 'string');

 

if ($mode == 'novinki')

{

$filter['featured'] = 1;

}

Вот это ПОСЛЕ

// GET-Параметры

$category_url = $this->request->get('category', 'string');

$brand_url = $this->request->get('brand', 'string');

 

if smarty server и прочую чушь из шаблона выкинуть НАФИГ, работать будет СТАНДАРТНЫЙ products.tpl

Ссылка на сообщение
Поделиться на другие сайты

Все изменил, но теперь у меня в новинках выводятся рекомендуемые, тоже самое, что в каталоге. http://choosemood.ru/novinki

Что нужно поменять чтобы выводились новинки. Заранее благодарен за люую помощь.

Ссылка на сообщение
Поделиться на другие сайты

Как в стандартной функции function get_new_products_plugin во view.php. Сейчас добавил также лови момент он работает аналогично, вывод товаров происходит такой же как и на странице  каталога http://choosemood.ru/products Как сделать так, чтобы при выводе новинок и дисконтных товаров вывод происходил как в функции function get_new_products_plugin во view.php и соответственно function get_discounted_products_plugin Заранее благодарен за любую помощь.

Ссылка на сообщение
Поделиться на другие сайты
  • 7 месяцев спустя...

Сделал как написано Kosjak76, но по прежнему в таком случае выводит Бог знает что.

Мне нужно сделать две страницы с товарами:

1. Товар со скидками

2. Популярный товар (рекомендуемый)

 

Или в этом способе подразумевается создание фильтра для товаров и отдельное проставление его?

Ссылка на сообщение
Поделиться на другие сайты

В этом способе подразумевается вывод рекомендуемых.

Этот способ 100% рабочий, работает не на одном десятке сайтов.

Дайте ссылку, посмотрим, что у вас не так.

Ссылка на сообщение
Поделиться на другие сайты

К большому сожалению не могу показать страницу, она на локальной машине.

Но ситуация такая, что я в файле ProductsView.php 

После строки $brand_url    = $this->request->get('brand', 'string');

Вставил:

mode = $this->request->get('mode', 'string');
        
        if ($mode == 'hits')
            {
            $filter['featured'] = 1;
            
            }

В файле .htaccess через Notepad++

RewriteRule ^hits/?$ index.php?module=ProductsView&mode=hits [L,QSA]

Создал страницу с названием hits

 

Вхожу по адресу olololo.com/hits и вижу все товары что у меня есть на одной странице...

Всё верно сделал?

Ссылка на сообщение
Поделиться на другие сайты

 

<?PHP

/**
 * Simpla CMS
 *
 * @copyright     2011 Denis Pikusov
 * @link         http://simplacms.ru
 * @author         Denis Pikusov
 *
 * Этот класс использует шаблон products.tpl
 *
 */

require_once('View.php');

class ProductsView extends View
{
     /**
     *
     * Отображение списка товаров
     *
     */    
    function fetch()
    {
        // GET-Параметры
        $category_url = $this->request->get('category', 'string');
        $brand_url    = $this->request->get('brand', 'string');
        $mode = $this->request->get('mode', 'string');
        
        if ($mode == 'hits')
            {
            $filter['featured'] = 1;
            
            }
        
        $filter = array();
        $filter['visible'] = 1;    

        // Если задан бренд, выберем его из базы
        if (!empty($brand_url))
        {
            $brand = $this->brands->get_brand((string)$brand_url);
            if (empty($brand))
                return false;
            $this->design->assign('brand', $brand);
            $filter['brand_id'] = $brand->id;
        }
        
        // Выберем текущую категорию
        if (!empty($category_url))
        {
            $category = $this->categories->get_category((string)$category_url);
            if (empty($category) || (!$category->visible && empty($_SESSION['admin'])))
                return false;
            $this->design->assign('category', $category);
            $filter['category_id'] = $category->children;
        }

        // Если задано ключевое слово
        $keyword = $this->request->get('keyword');
        if (!empty($keyword))
        {
            $this->design->assign('keyword', $keyword);
            $filter['keyword'] = $keyword;
        }

        // Сортировка товаров, сохраняем в сесси, чтобы текущая сортировка оставалась для всего сайта
        if($sort = $this->request->get('sort', 'string'))
            $_SESSION['sort'] = $sort;        
        if (!empty($_SESSION['sort']))
            $filter['sort'] = $_SESSION['sort'];            
        else
            $filter['sort'] = 'position';            
        $this->design->assign('sort', $filter['sort']);
        
        // Свойства товаров
        if(!empty($category))
        {
            $features = array();
            foreach($this->features->get_features(array('category_id'=>$category->id, 'in_filter'=>1)) as $feature)
            { 
                $features[$feature->id] = $feature;
                if(($val = strval($this->request->get($feature->id)))!='')
                    $filter['features'][$feature->id] = $val;    
            }
            
            $options_filter['visible'] = 1;
            
            $features_ids = array_keys($features);
            if(!empty($features_ids))
                $options_filter['feature_id'] = $features_ids;
            $options_filter['category_id'] = $category->children;
            if(isset($filter['features']))
                $options_filter['features'] = $filter['features'];
            if(!empty($brand))
                $options_filter['brand_id'] = $brand->id;
            
            $options = $this->features->get_options($options_filter);

            foreach($options as $option)
            {
                if(isset($features[$option->feature_id]))
                    $features[$option->feature_id]->options[] = $option;
            }
            
            foreach($features as $i=>&$feature)
            { 
                if(empty($feature->options))
                    unset($features[$i]);
            }

            $this->design->assign('features', $features);
         }

        // Постраничная навигация
        $items_per_page = $this->settings->products_num;        
        // Текущая страница в постраничном выводе
        $current_page = $this->request->get('page', 'int');    
        // Если не задана, то равна 1
        $current_page = max(1, $current_page);
        $this->design->assign('current_page_num', $current_page);
        // Вычисляем количество страниц
        $products_count = $this->products->count_products($filter);
        
        // Показать все страницы сразу
        if($this->request->get('page') == 'all')
            $items_per_page = $products_count;    
        
        $pages_num = ceil($products_count/$items_per_page);
        $this->design->assign('total_pages_num', $pages_num);

        $filter['page'] = $current_page;
        $filter['limit'] = $items_per_page;
        
        ///////////////////////////////////////////////
        // Постраничная навигация END
        ///////////////////////////////////////////////
        

        $discount = 0;
        if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id'])))
            $discount = $user->discount;
            
        // Товары 
        $products = array();
        foreach($this->products->get_products($filter) as $p)
            $products[$p->id] = $p;
            
        // Если искали товар и найден ровно один - перенаправляем на него
        if(!empty($keyword) && $products_count == 1)
            header('Location: '.$this->config->root_url.'/products/'.$p->url);
        
        if(!empty($products))
        {
            $products_ids = array_keys($products);
            foreach($products as &$product)
            {
                $product->variants = array();
                $product->images = array();
                $product->properties = array();
            }
    
            $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true));
            
            foreach($variants as &$variant)
            {
                //$variant->price *= (100-$discount)/100;
                $products[$variant->product_id]->variants[] = $variant;
            }
    
            $images = $this->products->get_images(array('product_id'=>$products_ids));
            foreach($images as $image)
                $products[$image->product_id]->images[] = $image;

            foreach($products as &$product)
            {
                if(isset($product->variants[0]))
                    $product->variant = $product->variants[0];
                if(isset($product->images[0]))
                    $product->image = $product->images[0];
            }
                
    
            /*
            $properties = $this->features->get_options(array('product_id'=>$products_ids));
            foreach($properties as $property)
                $products[$property->product_id]->options[] = $property;
            */
    
            $this->design->assign('products', $products);
         }
        
        // Выбираем бренды, они нужны нам в шаблоне    
        if(!empty($category))
        {
            $brands = $this->brands->get_brands(array('category_id'=>$category->children));
            $category->brands = $brands;        
        }
        
        // Устанавливаем мета-теги в зависимости от запроса
        if($this->page)
        {
            $this->design->assign('meta_title', $this->page->meta_title);
            $this->design->assign('meta_keywords', $this->page->meta_keywords);
            $this->design->assign('meta_description', $this->page->meta_description);
        }
        elseif(isset($category))
        {
            $this->design->assign('meta_title', $category->meta_title);
            $this->design->assign('meta_keywords', $category->meta_keywords);
            $this->design->assign('meta_description', $category->meta_description);
        }
        elseif(isset($brand))
        {
            $this->design->assign('meta_title', $brand->meta_title);
            $this->design->assign('meta_keywords', $brand->meta_keywords);
            $this->design->assign('meta_description', $brand->meta_description);
        }
        elseif(isset($keyword))
        {
            $this->design->assign('meta_title', $keyword);
        }
        
            
        $this->body = $this->design->fetch('products.tpl');
        return $this->body;
    }
    
    

}

 

 

.htaccess

AddDefaultCharset UTF-8
ErrorDocument 404 /404
ErrorDocument 401 /password.php
RewriteEngine on


# Админка теперь по адресу /admin
RewriteRule    ^admin/?$  simpla [L]
RewriteRule ^hits/?$ index.php?module=ProductsView&mode=hits [L,QSA]


# Каталог товаров
RewriteRule ^catalog/([^/]+)/?$    index.php?module=ProductsView&category=$1 [L,QSA]
RewriteRule ^catalog/([^/]+)/([^/]+)/?$    index.php?module=ProductsView&category=$1&brand=$2 [L,QSA]


RewriteRule ^products/([^/]+)/?$    index.php?module=ProductView&product_url=$1 [L,QSA]
RewriteRule ^products/?$    index.php?module=ProductsView [L,QSA]


RewriteRule ^brands/([^/]+)/?$    index.php?module=ProductsView&brand=$1 [L,QSA]
RewriteRule ^brands/([^/]+)/page_([^/]+)/?$    index.php?module=ProductsView&brand=$1&page=$2 [L,QSA]


# Поиск товаров
RewriteRule ^search/([^/]+)/?$    index.php?module=ProductsView&keyword=$1 [L,QSA]
RewriteRule ^search/?$    index.php?module=ProductsView [L,QSA]


# Блог
RewriteRule ^blog/([^/]+)/?$    index.php?module=BlogView&url=$1 [L,QSA]
RewriteRule ^blog/?$    index.php?module=BlogView [L,QSA]


# Корзина и заказы
RewriteRule ^cart/?$    index.php?module=CartView   [L,QSA]
RewriteRule ^cart/([^/]+)/?$    index.php?module=CartView&add_variant=$1  [L,QSA]
RewriteRule ^cart/remove/([^/]+)/?$    index.php?module=CartView&delete_variant=$1  [L,QSA]
RewriteRule ^order/([^/]+)/?$    index.php?module=OrderView&url=$1  [L,QSA]
RewriteRule ^order/?$    index.php?module=OrderView  [L,QSA]


# Для пользователей
RewriteRule ^user/login/?$    index.php?module=LoginView  [L,QSA]
RewriteRule ^user/register/?$    index.php?module=RegisterView  [L,QSA]
RewriteRule ^user/logout/?$    index.php?module=LoginView&action=logout  [L,QSA]
RewriteRule ^user/password_remind/?$    index.php?module=LoginView&action=password_remind  [L,QSA]
RewriteRule ^user/password_remind/([0-9a-z]+)/?$    index.php?module=LoginView&action=password_remind&code=$1  [L,QSA]
RewriteRule ^user/?$    index.php?module=UserView  [L,QSA]


# Google sitemap
RewriteRule ^sitemap.xml?$    sitemap.php  [L,QSA]


# XML
RewriteRule ^yandex.xml?$    yandex.php  [L,QSA]


# feedback
RewriteRule ^contact/?$    index.php?module=FeedbackView  [L,QSA]


#downloads
RewriteRule ^order/([^/]+)/([^/]+)/?$    index.php?module=OrderView&url=$1&file=$2  [L,QSA]




# Статические страницы
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/?$    index.php?module=PageView&page_url=$1 [L,QSA]
RewriteRule ^/?$    index.php?module=MainView&page_url= [L,QSA]


# Ресайз картинок на лету
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^files/products/(.+) resize/resize.php?file=$1&token=%{QUERY_STRING}
#RewriteCond %{THE_REQUEST} ^GET\ (.*)files/products/(.*)\?([A-z0-9]*) 
#RewriteRule ^files/products/(.+) resize/resize.php?file=%2&token=%3 [L,NE]



 

 

Ссылка на сообщение
Поделиться на другие сайты

if ($mode == 'hits')
{
$filter['featured'] = 1;

}

$filter = array();
$filter['visible'] = 1;

Вот это - бред...

$filter = array(); эта строка очищает полностью массив $filter

Правильно нужно так:

 

$filter = array();
$filter['visible'] = 1;

if ($mode == 'hits')
{
$filter['featured'] = 1;

}

Ссылка на сообщение
Поделиться на другие сайты

:o будешь в Киеве, угощу пивом/соком! )) Спасибо!

 

А что бы скидки фильтровать. делаем так:

 

ProductsView.php

$mode2 = $this->request->get('mode2', 'string');

if ($mode3 == 'discounted')
        {
        $filter['discounted'] = 1;


        }

 

.htaccess

RewriteRule ^discounted/?$ index.php?module=ProductsView&mode2=discounted [L,QSA]

 

olololo.com/discounted :)

Ссылка на сообщение
Поделиться на другие сайты
  • 1 год спустя...

Народ добрый верер! нужна помощь!!!!!!

<a data-product="{$product->id}" href="products/{$product->url}"><input type ="submit" value="подробнее" class="butt"/> </a>

мне нужно что бы при клике я попадал в раздел подробнее о товаре а меня несет добавлять товар в корзину..........где мой косяк?

Ссылка на сообщение
Поделиться на другие сайты

Народ добрый верер! нужна помощь!!!!!!

мне нужно что бы при клике я попадал в раздел подробнее о товаре а меня несет добавлять товар в корзину..........где мой косяк?

 

<a data-product="{$product->id}" href="products/{$product->url}">подробнее</a>
Ссылка на сообщение
Поделиться на другие сайты

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

Гость
Ответить в этой теме...

×   Вставлено с форматированием.   Вставить как обычный текст

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

Загрузка...
×
×
  • Создать...