Как мне создать шаблон для OpenCart? - PullRequest
22 голосов
/ 31 марта 2011

Я новичок в OpenCart, и я хотел бы применить свою тему к OpenCart.

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

Ответы [ 4 ]

31 голосов
/ 18 июня 2011

Балан, вы можете начать с копирования каталога каталога \ view \ theme \ default и всех его подпапок и т. Д.

Так что копия будет вашей новой темой. Допустим, у вас есть эти папки

catalog\view\theme\default
catalog\view\theme\my-new-theme
  1. Перейдите на сайт администратора и выберите Система> Настройки

  2. На вкладке «Магазин» вы должны увидеть опции «default» и «my-new-theme» в качестве опций для поля с именем «Шаблон». Выберите «my-new-theme» и сохраните.

  3. Начните вносить изменения в файлы в каталоге \ view \ theme \ my-new-theme, и они сразу появятся

17 голосов
/ 03 июля 2013

Создание пользовательской темы в opencart:

В Opencart используется резервная функция, это означает, что когда opencart не находит определенный шаблон в вашей теме, он будет найден в папке темы по умолчанию.Таким образом, чтобы создать новую тему, вам не нужно копировать все файлы из темы по умолчанию.Но создание темы - это не только создание новой папки и изменение ее цвета.В этом уроке мы узнаем основы понимания работы контроллера и модели, это связано с модификацией шаблона.

Прежде чем мы продолжим, я хочу прояснить, что тема в этом уроке относится к теме в папке темы(catalog / view / theme / mytheme) и шаблон ссылаются на файл .tpl внутри папки с шаблоном (catalog / view / theme / yourtheme / template).

Шаг 1. Создайте "Very" Basic Theme

    Create new folder mytheme on catalog/view/theme/, the folder tree will be like this:

        catalog/view/theme/
            |-> default
            |-> mytheme
    Now go to Admin -> System -> Setting - > Edit Store ->Tab Store -> template -> mytheme.
    Refresh your frontpage. Maybe your site litle bit mess, but your new theme is work!! :)

Шаг 2. Основная тема

    Make folder and copy some files from default theme, but DO NOT copy all files. Follow this folder tree:

        catalog/view/theme/
            |-> default
            |-> mytheme
                |-> image/*.* - copy all image
                |-> stylesheet/*.* - copy all stylesheet
                |-> template
                    |-> common
                        |-> header.tpl
        Note:
        We need to copy all the images because it's required by stylesheet.css.
        We need to copy IE stylesheet since it's declared on header.tpl (remove the file when you removing the IE style at header.tpl)
        We neet to copy slideshow.css and carousel.css since it's needed by opencart module.
        Rating star image is hard-coded into Page: category, manufacturer_info, product, review, search, special; Module: bestseller, featured, latest, special. It's up to you whether including those module and page to your theme and used another rating image, or just replacing use default rating star image.
    Now open header.tpl with text editor.
    Search word default and replace with mytheme
    Refresh your frontpage, and everything should be the same as when you used the default theme.
    To get different visual like changing color etc, you can modificate mytheme/stylesheet/stylesheet.css

Шаг 3. Шаблон настройки (1): Общие сведения о контроллере

    What template (*.tpl) is need to customize for a "good theme" ? Well, the answer is relative. In step 2 we already and only customizing the header.tpl. The most important rule to remember is never edit default theme template. Copy what you need to your theme folder, see example bellow.

        catalog/view/theme/
            |-> default
            |-> mytheme
                |-> image
                |-> stylesheet
                |-> template
                    |-> common
                        |-> header.tpl
                        |-> footer.tpl|-> information
                        |-> information.tpl|-> product
                        |-> product.tpl
                        |-> category.tpl
                        |-> manufacturer_list.tpl
    To customizing template and work with the controller, you need to understand that opencart used push-based MVC model -CMIIW.
    In quick explanation:
        When you accessing route=product/category url, opencart call controller/product/category.php file.
        This controller (ex. category.php) will decide which MV-L: Model, View (tpl), language will be load. In category controller (category.php) load:
            3 Model (category, product, image): $this->load->model('...');
            2 View (category.tpl & not_found.tpl): $this->template = '...';
            1 Language: $this->language->load('...')
        The controller also decide what data will be pushed into template and how user input will be processed.
            $this->$this->data['text_price'] = $this->language->get('text_price'); will produce Price in template: <?php echo $text_price; ?>
            When you change the product show (from 15 to 25) at frontpage, controller catch the request with if (isset($this->request->get['limit'])) { ... } then process it $this->data['limits'][] = array(... 'value' => 25, ...);
    Remember that there is no fallback function for controller. If you modificate the controller file manually, it will be replaced when you upgrade the opencart. Instead modificate it manually, you can used vQmod to make "virtual modification". We will talk this on step 5.

Шаг 4. Шаблон настройки (2): Общие сведенияМодель

    A Model in MVC in charge to pull and push data to database. Before controller get or post a data through model, the spesific model need to be loaded.
        load model: $this->load->model('catalog/product');
        get data: $this->model_catalog_product->getTotalProducts()
        post data: $this->model_catalog_product->editProduct()
    $this->load->model('catalog/product') tell the opencart to load model/catalog/product.php either in admin or catalog controller. getTotalProducts(), editProduct() is a function inside the model/catalog/product.php.
    Now open model/catalog/product.php and find public function getProduct.
        See list after return array, and you will found all product data.
        The question is, if the getProduct() listed all product data, why it doesn't show at category page (frontpage)? This because the category controller decide not to show all data.
        Open controller/product/category.php, find $this->data['products'][] = array to see what product data is used by controller.

Шаг 5. Шаблон настройки (3): Понимание vQmod

    vQmod is a virtual modificate and usually used to make some change to non-fallback file like controller and model without modificating the default file.
    You can download latest version and read further explanation about vQmod here.
    To install vQmod, copy vqmod folder inside the package to opencart root.

        yoursite
            |-> admin
            |-> catalog
            |-> download
            |-> image
            |-> system
            |-> vqmod
    Go to your browser and access: http://localhost/yoursite/vqmod/install. You will see success message: vQmod has been installed on your system!
    On the vQmod package, you will see folder docs and example to give you a refference how vQmod work. Here I will give you some quick refference:
        vQmod File is an .xml file stored at vqmod/xml folder. When executed, the vQmod force opencart to use the modification instead the default file (original file) and produce cache file at vqmod/vqcache.
        One vQmod File able to modificate multiple file; within one file, vQmod able to do multiple modificate operation.
        Example structure inside a vQmod File:
        <modification>
            <id>vQmod File ID</id>
            <version>1.0.0</version> --> vQmod File version
            <vqmver>1.0.8</vqmver> --> minimum vQmod version to work
            <author>your name</author>
            <file name="catalog/controller/product/category.php "> --> the file to modify
                <operation>
                    <search position="replace"><![CDATA[
                    search this code and replace it with code bellow
                    ]]></search>
                    <add><![CDATA[
                    add this new code to replace code above
                    ]]></add></operation>
                <operation>
                    <search position="after"><![CDATA[
                    search this code and add code bellow after it
                    ]]></search>
                    <add><![CDATA[
                    add this new code after code searched above
                    ]]></add></operation></file>
            <file name="...">
                <operation>
                    <search position="before"><![CDATA[
                    search this code and add code bellow before it
                    ]]></search>
                    <add><![CDATA[
                    add this new code before code searched above
                    ]]></add></operation></file></modification>
2 голосов
/ 24 апреля 2013

Помните, что все файлы в представлении заканчиваются расширением .tpl.

Значения переменных в файлах tpl получены от соответствующих контроллеров.Принимая во внимание, что значения переменных в контроллере происходят из модели, которая извлекает данные из базы данных.

Так что, если вы вносите какие-либо изменения в имя переменной в файлах tpl, измените имя переменной в соответствующих файлах контроллера также.

1 голос
/ 10 октября 2013

@ JackLB - Вы можете называть файлы шаблонов по своему желанию. Каждый шаблон в любом случае указывается вручную в файле контроллера.

Попробуйте найти .tpl в любом файле контроллера, и вы увидите:

if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . 
'/template/common/header.tpl')) {
        $this->template = $this->config->get('config_template') . 
'/template/common/header.tpl';
    } else {
        $this->template = 'default/template/common/header.tpl';
    }

Opencart ищет шаблон в папке пользовательских шаблонов. Если не найден, он возвращается к шаблону по умолчанию. Если не найден, будет показана ошибка.

Измените путь к месту соответственно.

Но это сложнее - использовать одно и то же наименование для контроллера / шаблона.

...