Как да създам шаблон за OpenCart?

Нов съм в OpenCart и бих искал да приложа моята тема към OpenCart.

Знам, че не трябва да редактирам директно шаблона по подразбиране, но как да копирам файловете на шаблона по подразбиране и да го променя, за да приложа темата?


person balanv    schedule 31.03.2011    source източник


Отговори (4)


Балан, можеш да започнеш, като копираш папката catalog\view\theme\default и всички нейни подпапки файлове и т.н.

Така че копието ще бъде вашата нова тема. Да кажем, че вече имате тези папки

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

  2. В раздела „Магазин“ трябва да видите опциите „по подразбиране“ и „моята-нова-тема“ като опции за полето с име „Шаблон“. Изберете „моята-нова-тема“ и запазете.

  3. Започнете да правите промени във файловете под catalog\view\theme\my-new-theme и те ще се появят веднага

person Brad    schedule 18.06.2011

Създаване на персонализирана тема в opencart:

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

Преди да продължим, искам да изясня, че темата в този урок се отнася до темата в папката на темата (catalog/view/theme/mytheme), а шаблонът се отнася до .tpl файла в папката с шаблони (catalog/view/theme/ вашата тема/шаблон).

Стъпка 1. Изградете "Много" основна тема

    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>
person Roy M J    schedule 03.07.2013
comment
Здравей, Рой, твоите приятели наистина ми помагат. Искам да знам в opencart задължително ли е да има едно и също име за файла на контролера и файла за преглед (.tpl). Да кажем, че имам своя контролен файл static.php в 'catalog/controller/module/static.php', сега искам да изобразя резултатния масив и стойност във файл за изглед -› 'catalog\view\theme\my_theme\template\common\ home.tpl'. Така че възможно ли е да се направи това?? - person JackLB; 27.09.2013
comment
Да предположим, че искам да създам динамичен css style.php в 'catalog\view\theme\my_theme\stylesheet\style.php' Така че тук, мога ли да предам стойностите и масива от който и да е файл на контролера от контролера? благодаря за вашата помощ. - person JackLB; 27.09.2013
comment
@ArshadHussain, изглежда е същият автор. - person Pacerier; 02.10.2014

Не забравяйте, че всички файлове в изгледа завършват с разширение .tpl.

Стойностите на променливите в tpl файловете идват от съответните им контролери. Докато стойностите на променливите в контролера идват от модела, който извлича данните от базата данни.

Така че, ако направите някакви промени в името на променливата в tpl файловете, променете името на променливата в съответните файлове на контролера също.

person dulton    schedule 24.04.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 търси шаблон в персонализирана папка с шаблони. Ако не бъде намерен, той се връща към шаблона по подразбиране. Ако не бъде намерено, ще се покаже грешка.

Променете съответно пътя на местоположението.

Но това е по-сложно - да се използва същото именуване за контролер/шаблон.

person Arnis Juraga    schedule 10.10.2013