Jump to content

[Résolu] Peut t'on appeler un fichier php à partir d'un tpl


Recommended Posts

Bonjour,

 

Ci-après, la procédure à suivre pour inclure un fichier PHP à partir d'un fichiet template (*.tpl) :

 

  1. Ajouter le code suivant à la fin du fichier RACINE/config/smarty.config.inc.php
    function includeFile($params, &$smarty)
    {
        require_once 'chemin-vers-fichier-php.php';
    }
    
    smartyRegisterFunction($smarty, 'function', 'include_php_file', 'includeFile');
    
  2. Vous pouvez désormais utiliser, dans vos templates, le tag smarty {include_php_file}, là où vous souhaitez inclure votre fichier/code PHP.

 

NB : Si vous souhaitez utiliser votre fichier uniquement pour le FrontOffice, il est préférable d'utiliser le fichier RACINE/config/smartyfront.config.inc.php, et dans le même principe, utiliser le fichier RACINE/config/smartyadmin.config.inc.php, pour que votre fichier soit uniquement disponible dans le BackOffice.

Edited by Afrawan Artisan (see edit history)
Link to comment
Share on other sites

Bonjour et merci beaucoup pour votre aide.

 

J'ai donc suivi pas à pas vos explications, seulement je dois faire quelque chose de travers.

 

J'appelle donc bien mon fichier.php via le fichier product.tpl, mais cela me provoque une page blanche. Je suis navré je ne suis pas très fort, y a t'il des balises à rajouter dans le tpl ou autre chose ?

 

Dans mon tpl je tape ceci : <?php {include_php_file='/monrépertoire/contact.php'}  ?> ou meme sans balise :  {include_php_file='/monrépertoire/contact.php'} 

 

En vous remerciant par avance

Edited by saitis (see edit history)
Link to comment
Share on other sites

Ci-après le code, en fonction des données que vous avez fournis :

function includeContact($params, &$smarty)
{
    require_once '/monrépertoire/contact.php';
}

smartyRegisterFunction($smarty, 'function', 'include_contact', 'includeContact');

Ensuite, dans votre template, il vous suffit d'intégrer le tage suivant {include_contact}, sans paramètres, uniquement ce tag.

  • Like 1
Link to comment
Share on other sites

merci, ma page product est revenue. cependant rien à faire, mon script n'apparait toujours pas.

si vous voulez voir, si vous avez un peu de temps, voici le lien http://www.graphicsperso.stickers-is.com/home/122-suppression-bruits-de-fond.html

Le script devrait appraitre là ou j'ai mis 12345

 

Par ailleurs mes fichiers smartyfront.config.inc.php, etc sont dans un répertoire par défaut : Répertoire Config (peut être que cela joue sur quelque chose, je ne sais pas)

 

Je suis en V1.6

 

C'est une boutique vierge donc je n'ai pas grand chose dessus.

 

Et là c'est le fichier php que je voudrai faire apparaitre dans ma fiche product : http://www.graphicsperso.stickers-is.com/contactttt/contact.php

 

Donc si j'ai bien suivi, le code donne cela :

 

 

function includeFile($params, &$smarty)
{
    require_once '/contactttt/contact.php';
}
smartyRegisterFunction($smarty, 'function', 'include_contact', 'includeContact');

Edited by saitis (see edit history)
Link to comment
Share on other sites

Je viens d'essayer plusieurs arborescence, je comprends pas ce qui se passe, toujours pas de script.

Le pire c'est que c'est le point crucial de ma future activité.

 

Je ne sais plus quoi essayer d'autre. Quelqu'un aurait t'il une idée de ce qui pourrait clocher svp ?

 

Je joue sur les option Smart cache" pour les feuilles de style, "Smart cache" pour le code JavaScript....

 

Ainsi que sur les options Ne jamais recompiler les fichiers de templates

Recompiler les fichiers de templates s'ils ont été mis à jour

Forcer la compilation à chaque appel

 

Vraiment je vois pas...!

Edited by saitis (see edit history)
  • Sad 1
Link to comment
Share on other sites

Le dossier renseigné dans require_once '/contactttt/contact.php'; doit être relatif au dossier config/.

 

Si votre dossier 'contactttt/contact.php' est à la racine de votre site, alors, vous devez utiliser le chemin suivant : '../contactttt/contact.php'

Link to comment
Share on other sites

Je vous remercie à nouveau d'essayer de m'aider :)

 

Je comprends bien la logique du truc.

 

Bon, c'est bien simple j'ai fini par copier le fichier contact.php de partout comme ca.

 

Et j'ai beau changé d'arboescence, chemin relatif ou en dur...

J'ai essayé via les deux fichiers : smartyfront.config.inc.php ou smarty.config.inc.php

 

Et ca prend toujours pas... Truc de fou... Là je déserpère...

Edited by saitis (see edit history)
Link to comment
Share on other sites

Ah désolé, une petite erreur de ma part dans le chemin :

function includeContact($params, &$smarty)
{
    require_once _PS_ROOT_DIR_.'contactttt/contact.php';
}

smartyRegisterFunction($smarty, 'function', 'include_contact', 'includeContact');

Normalement, ça devrait être bon.

Link to comment
Share on other sites

Hélas toujours pas.

 

Bizarre que les 2 champs que j'appelle dans mon php ne s'affiche pas.

 

Le pire c'est que ca m'affiche même pas une erreur pour savoir ce qui clocherait !!

 

Ca reste un mystère..!

 

Bon au cas ou, je vous met le code de mes fichiers smarty :

 

smarty.config.inc.php

 

<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <[email protected]>
*  @copyright  2007-2015 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

define('_PS_SMARTY_DIR_', _PS_TOOL_DIR_.'smarty/');

require_once(_PS_SMARTY_DIR_.'Smarty.class.php');

global $smarty;
$smarty = new Smarty();
$smarty->setCompileDir(_PS_CACHE_DIR_.'smarty/compile');
$smarty->setCacheDir(_PS_CACHE_DIR_.'smarty/cache');
if (!Tools::getSafeModeStatus())
    $smarty->use_sub_dirs = true;
$smarty->setConfigDir(_PS_SMARTY_DIR_.'configs');
$smarty->caching = true;
if (Configuration::get('PS_SMARTY_CACHING_TYPE') == 'mysql')
{
    include(_PS_CLASS_DIR_.'/SmartyCacheResourceMysql.php');
    $smarty->caching_type = 'mysql';
}
$smarty->force_compile = (Configuration::get('PS_SMARTY_FORCE_COMPILE') == _PS_SMARTY_FORCE_COMPILE_) ? true : false;
$smarty->compile_check = (Configuration::get('PS_SMARTY_FORCE_COMPILE') >= _PS_SMARTY_CHECK_COMPILE_) ? true : false;
$smarty->debug_tpl = _PS_ALL_THEMES_DIR_.'debug.tpl';

/* Use this constant if you want to load smarty without all PrestaShop functions */
if (defined('_PS_SMARTY_FAST_LOAD_') && _PS_SMARTY_FAST_LOAD_)
    return;

if (defined('_PS_ADMIN_DIR_'))
    require_once (dirname(__FILE__).'/smartyadmin.config.inc.php');
else
    require_once (dirname(__FILE__).'/smartyfront.config.inc.php');

smartyRegisterFunction($smarty, 'modifier', 'truncate', 'smarty_modifier_truncate');
smartyRegisterFunction($smarty, 'modifier', 'secureReferrer', array('Tools', 'secureReferrer'));

smartyRegisterFunction($smarty, 'function', 't', 'smartyTruncate'); // unused
smartyRegisterFunction($smarty, 'function', 'm', 'smartyMaxWords'); // unused
smartyRegisterFunction($smarty, 'function', 'p', 'smartyShowObject'); // Debug only
smartyRegisterFunction($smarty, 'function', 'd', 'smartyDieObject'); // Debug only
smartyRegisterFunction($smarty, 'function', 'l', 'smartyTranslate', false);
smartyRegisterFunction($smarty, 'function', 'hook', 'smartyHook');
smartyRegisterFunction($smarty, 'function', 'toolsConvertPrice', 'toolsConvertPrice');
smartyRegisterFunction($smarty, 'modifier', 'json_encode', array('Tools', 'jsonEncode'));
smartyRegisterFunction($smarty, 'modifier', 'json_decode', array('Tools', 'jsonDecode'));
smartyRegisterFunction($smarty, 'function', 'dateFormat', array('Tools', 'dateFormat'));
smartyRegisterFunction($smarty, 'function', 'convertPrice', array('Product', 'convertPrice'));
smartyRegisterFunction($smarty, 'function', 'convertPriceWithCurrency', array('Product', 'convertPriceWithCurrency'));
smartyRegisterFunction($smarty, 'function', 'displayWtPrice', array('Product', 'displayWtPrice'));
smartyRegisterFunction($smarty, 'function', 'displayWtPriceWithCurrency', array('Product', 'displayWtPriceWithCurrency'));
smartyRegisterFunction($smarty, 'function', 'displayPrice', array('Tools', 'displayPriceSmarty'));
smartyRegisterFunction($smarty, 'modifier', 'convertAndFormatPrice', array('Product', 'convertAndFormatPrice')); // used twice
smartyRegisterFunction($smarty, 'function', 'getAdminToken', array('Tools', 'getAdminTokenLiteSmarty'));
smartyRegisterFunction($smarty, 'function', 'displayAddressDetail', array('AddressFormat', 'generateAddressSmarty'));
smartyRegisterFunction($smarty, 'function', 'getWidthSize', array('Image', 'getWidth'));
smartyRegisterFunction($smarty, 'function', 'getHeightSize', array('Image', 'getHeight'));
smartyRegisterFunction($smarty, 'function', 'addJsDef', array('Media', 'addJsDef'));
smartyRegisterFunction($smarty, 'block', 'addJsDefL', array('Media', 'addJsDefL'));
smartyRegisterFunction($smarty, 'modifier', 'boolval', array('Tools', 'boolval'));

function smartyDieObject($params, &$smarty)
{
    return Tools::D($params['var']);
}

function smartyShowObject($params, &$smarty)
{
    return Tools::P($params['var']);
}

function smartyMaxWords($params, &$smarty)
{
    Tools::displayAsDeprecated();
    $params['s'] = str_replace('...', ' ...', html_entity_decode($params['s'], ENT_QUOTES, 'UTF-8'));
    $words = explode(' ', $params['s']);

    foreach($words AS &$word)
        if(Tools::strlen($word) > $params['n'])
            $word = Tools::substr(trim(chunk_split($word, $params['n']-1, '- ')), 0, -1);

    return implode(' ',  Tools::htmlentitiesUTF8($words));
}

function smartyTruncate($params, &$smarty)
{
    Tools::displayAsDeprecated();
    $text = isset($params['strip']) ? strip_tags($params['text']) : $params['text'];
    $length = $params['length'];
    $sep = isset($params['sep']) ? $params['sep'] : '...';

    if (Tools::strlen($text) > $length + Tools::strlen($sep))
        $text = Tools::substr($text, 0, $length).$sep;

    return (isset($params['encode']) ? Tools::htmlentitiesUTF8($text, ENT_NOQUOTES) : $text);
}

function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false, $charset = 'UTF-8')
{
    if (!$length)
        return '';

    $string = trim($string);

    if (Tools::strlen($string) > $length)
    {
        $length -= min($length, Tools::strlen($etc));
        if (!$break_words && !$middle)
            $string = preg_replace('/\s+?(\S+)?$/u', '', Tools::substr($string, 0, $length+1, $charset));
        return !$middle ? Tools::substr($string, 0, $length, $charset).$etc : Tools::substr($string, 0, $length/2, $charset).$etc.Tools::substr($string, -$length/2, $length, $charset);
    }
    else
        return $string;
}

function smarty_modifier_htmlentitiesUTF8($string)
{
        return Tools::htmlentitiesUTF8($string);
}
function smartyMinifyHTML($tpl_output, &$smarty)
{
    if (in_array(Context::getContext()->controller->php_self, array('pdf-invoice', 'pdf-order-return', 'pdf-order-slip')))
        return $tpl_output;
    $tpl_output = Media::minifyHTML($tpl_output);
    return $tpl_output;
}

function smartyPackJSinHTML($tpl_output, &$smarty)
{
    if (in_array(Context::getContext()->controller->php_self, array('pdf-invoice', 'pdf-order-return', 'pdf-order-slip')))
        return $tpl_output;
    $tpl_output = Media::packJSinHTML($tpl_output);
    return $tpl_output;
}

function smartyRegisterFunction($smarty, $type, $function, $params, $lazy = true)
{
    if (!in_array($type, array('function', 'modifier', 'block')))
        return false;

    // lazy is better if the function is not called on every page
    if ($lazy)
    {
        $lazy_register = SmartyLazyRegister::getInstance();
        $lazy_register->register($params);

        if (is_array($params))
            $params = $params[1];

        // SmartyLazyRegister allows to only load external class when they are needed
        $smarty->registerPlugin($type, $function, array($lazy_register, $params));
    }
    else
        $smarty->registerPlugin($type, $function, $params);
}

function smartyHook($params, &$smarty)
{
    if (!empty($params['h']))
    {
        $id_module = null;
        $hook_params = $params;
        $hook_params['smarty'] = $smarty;
        if (!empty($params['mod']))
        {
            $module = Module::getInstanceByName($params['mod']);
            if ($module && $module->id)
                $id_module = $module->id;
            unset($hook_params['mod']);
        }
        unset($hook_params['h']);
        return Hook::exec($params['h'], $hook_params, $id_module);
    }
}

function toolsConvertPrice($params, &$smarty)
{
    return Tools::convertPrice($params['price'], Context::getContext()->currency);
}

/**
 * Used to delay loading of external classes with smarty->register_plugin
 */
class SmartyLazyRegister
{
    protected $registry = array();
    protected static $instance;

    /**
     * Register a function or method to be dynamically called later
     * @param string|array $params function name or array(object name, method name)
     */
    public function register($params)
    {
        if (is_array($params))
            $this->registry[$params[1]] = $params;
        else
            $this->registry[$params] = $params;
    }

    /**
     * Dynamically call static function or method
     *
     * @param string $name function name
     * @param mixed $arguments function argument
     * @return mixed function return
     */
    public function __call($name, $arguments)
    {
        $item = $this->registry[$name];

        // case 1: call to static method - case 2 : call to static function
        if (is_array($item[1]))
            return call_user_func_array($item[1].'::'.$item[0], array($arguments[0], &$arguments[1]));
        else
        {
            $args = array();
            
            foreach($arguments as $a => $argument)
                if($a == 0)
                    $args[] = $arguments[0];
                else
                    $args[] = &$arguments[$a];
            
            return call_user_func_array($item, $args);
        }
    }

    public static function getInstance()
    {
        if (!self::$instance)
            self::$instance = new SmartyLazyRegister();
        return self::$instance;
    }
}

 

 

 

 

et : smartyfront.config.inc.php

 

<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <[email protected]>
*  @copyright  2007-2015 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

global $smarty;
$smarty->setTemplateDir(_PS_THEME_DIR_.'tpl');

if (Configuration::get('PS_HTML_THEME_COMPRESSION'))
    $smarty->registerFilter('output', 'smartyMinifyHTML');
if (Configuration::get('PS_JS_HTML_THEME_COMPRESSION'))
    $smarty->registerFilter('output', 'smartyPackJSinHTML');

function smartyTranslate($params, &$smarty)
{
    global $_LANG;

    if (!isset($params['js']))
        $params['js'] = false;
    if (!isset($params['pdf']))
        $params['pdf'] = false;
    if (!isset($params['mod']))
        $params['mod'] = false;
    if (!isset($params['sprintf']))
        $params['sprintf'] = null;

    $string = str_replace('\'', '\\\'', $params['s']);
    $filename = ((!isset($smarty->compiler_object) || !is_object($smarty->compiler_object->template)) ? $smarty->template_resource : $smarty->compiler_object->template->getTemplateFilepath());

    $basename = basename($filename, '.tpl');
    $key = $basename.'_'.md5($string);

    if (isset($smarty->source) && (strpos($smarty->source->filepath, DIRECTORY_SEPARATOR.'override'.DIRECTORY_SEPARATOR) !== false))
        $key = 'override_'.$key;

    if ($params['mod'])
        return Translate::smartyPostProcessTranslation(Translate::getModuleTranslation($params['mod'], $params['s'], $basename, $params['sprintf'], $params['js']), $params);
    else if ($params['pdf'])
        return Translate::smartyPostProcessTranslation(Translate::getPdfTranslation($params['s']), $params);

    if ($_LANG != null && isset($_LANG[$key]))
        $msg = $_LANG[$key];
    elseif ($_LANG != null && isset($_LANG[Tools::strtolower($key)]))
        $msg = $_LANG[Tools::strtolower($key)];
    else
        $msg = $params['s'];

    if ($msg != $params['s'] && !$params['js'])
        $msg = stripslashes($msg);
    elseif ($params['js'])
        $msg = addslashes($msg);

    if ($params['sprintf'] !== null)
        $msg = Translate::checkAndReplaceArgs($msg, $params['sprintf']);

    return Translate::smartyPostProcessTranslation($params['js'] ? $msg : Tools::safeOutput($msg), $params);
}








Sait t'on jamais !!!

   

Edited by saitis (see edit history)
Link to comment
Share on other sites

Bon visiblement ca prend quelquechose mais ca me flingue cette fois une grosse partie de ma page product.

 

J'ai fini par mettre un simple echo '' dans mon fichier php pour voir, même cela, ca n'apparait pas à l'écran...

 

Donc au final, j'y comprends plus rien sur ce qui pourrait se passer.

 

Peut être que j'ai tout faux depuis le départ à vouloir faire apparaitre 2 champs supplémentaire dans ma fiche product...

Edited by saitis (see edit history)
Link to comment
Share on other sites

Du coup,

 

si quelqu'un connait un script en tpl que je pourrai intégrer directement dans mon product.tpl,

 

pour faire en sorte que les clients puissent m'envoyer des fichiers mp3, wav soit par messagerie soit par upload sur serveur, ce serait cool, là je suis coincé. (J'avais déjà essayé avec l'existant mais impossible d'envoyer autre que des jpg, gif.

 

En vous remerciant à nouveau :)

Link to comment
Share on other sites

Je vous fais un dernier retour pour vous informer que caaaaa yeeesstttt ca fonctionne :)

 

J'ai fais une grosse pause, puis j'ai tous supprimer pour tout refaire de zéro. Je suspecte que le smarty devait être un peu dans les choux car j'ai refais exactement la même chose qu'au début après avoir tout nettoyé, supprimer et vidanger dans tous les sens.

 

Mille merci vraiment pour m'avoir aidé tout au long de cette longue journée Afrawan :)

  • Like 1
Link to comment
Share on other sites

Aieaieaie, je pense que c'est bien un soucis de cache mais là par exemple alors que je bossais pas dessus j'ai juste rafraichi et hop page mi blanche à nouveau.

 

Je vous embete une fois à nouveau, du coup, si vous pouviez me dire quelles options gérer par rapport au cache pour retrouver ma page normalement s'il vous plait ?

 

Ca m'a l'air bien compliqué cette histoire de cache

Edited by saitis (see edit history)
  • Sad 1
Link to comment
Share on other sites

  • 2 years later...

Stop ! Change de méthode, là ça part dans tous les sens.

Tu te réponds à toi même et tu t'auto-cites sur un topic qui date de 2015.

1. Les forumeurs à qui tu t'adresses n'ont certainement pas mis un pied ici depuis 2 ans au moins

2. La solution qu'ils ont donné est à moitié moisie. Ca fait 6 ans que je fais du Prestashop et je n'ai jamais utilisé ce bricolage consistant à enregistrer des fonctions Smarty. C'est pas comme ça qu'on fait.

Donc là tu respires, tu arrêtes de paniquer et tu crées ton propre topic où tu expliques :

1. Ce que tu essayes de faire

2. Pourquoi tu as besoin de le faire

Avec des phrases explicatives, des détails, du point par point. Et pas des "quand je copie/colle du code dégueulasse que j'ai trouvé au hasard sur le net ça marche pas".

Plus tu seras synthétique et calme, plus on pourra t'aider à trouver une solution. Mais pour ça il faut que tu formules bien ton problème.

Ah et tu vires tous les bouts de code pourri que tu as dû disperser un peu partout.

Link to comment
Share on other sites

OK on progresse.

Maintenant tu crées un nouveau topic, avec un titre très explicite (et pas "HELP, erreur Smarty" ou "Problème produits").

Dans ce topic tu remets la même explication que tu viens de donner mais en plus tu précises de quel module tu parles.

Sachant que la commande de back-office est une fonctionnalité native de PS. Je suppose que tu le sais et que tu l'as déjà essayé...

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...