OpenCart - View alternate product template based on arbitrary product field

你。 提交于 2019-12-02 22:56:18

问题


There is another post on Stack Overflow that includes the following code for serving multiple product templates based on product ID

//42 is the id of the product
if ($this->request->get['product_id'] == 42) {
    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/customproduct.tpl')) {
        $this->template = $this->config->get('config_template') . '/template/product/customproduct.tpl';
    } else {
        $this->template = 'default/template/product/customproduct.tpl';
    }
} else {
    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/product.tpl')) {
        $this->template = $this->config->get('config_template') . '/template/product/product.tpl';
    } else {
        $this->template = 'default/template/product/customproduct.tpl';
    }
}

I would like to check for an alternate product field value that I won't be using instead of ID so it is something that can be managed from the admin panel.

For example, a statement that reads "If product location = accessory then get product/accessory.tpl"

Would I have to load that field in the product controller before I can request it with the if statement?

What would the syntax look like?


回答1:


You should be able to use any of the fields in product data in the admin panel such as Location that you already referenced.

Everything from the product table for your requested row should be present in the $product_info array.

Try something like this:

$template = ($product_info['location'] == 'accessory') ? 'accessory.tpl' : 'product.tpl';

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

If you anticipate there will be many different templates for different locations it would be more efficient to use a switch control.

switch ($product_info['location']):
    case 'accessory':
        $template = 'accessory.tpl';
        break;
    case 'tool':
        $template = 'tool.tpl';
        break;
    default:
        $template = 'product.tpl';
        break;
endswitch;

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

Hope that helps.



来源:https://stackoverflow.com/questions/18188311/opencart-view-alternate-product-template-based-on-arbitrary-product-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!