简体   繁体   中英

Joomla 3 load template in external file

I have created an external file. I want to load joomla default template in that file. I used below code, and it caused an error:

Fatal error: Call to protected method JApplicationSite::render() from context ' '

define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define('JPATH_BASE', realpath(dirname(__FILE__) ));
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$mainframe = JFactory::getApplication('site');
JPluginHelper::importPlugin('system');
$mainframe->initialise();

$myContent = "Hello World!!";
$document = JFactory::getDocument();
$document->setBuffer($myContent, 'component');

$mainframe->render();
echo $mainframe;

At the least you need to let the Joomla app know which template you'd like to render.

//normal external script initialisation
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath('/home/somepath/public_html/somedirectory/'));
define( 'DS', DIRECTORY_SEPARATOR ); 
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php');
require_once( JPATH_LIBRARIES .DS.'joomla'.DS.'factory.php');
$app = JFactory::getApplication('site');
$app->initialise();

//jimport( 'joomla.document.html.html' ); required in certain cases
//initialise the doc to use the Html renderer
$doc = new JDocumentHtml();

//minimal info required
$options['directory'] = "/my/template/directory";
$options["template"] = $app->getTemplate();//get the template name
$options["file"] = "index.php";//usually

//Optional: Manually set params
//$params = new JRegistry();
//$params->colorVariation = "blue";
//$params->widthStyle = "fluid";
//$params->showComponent = "1";
//$options["params"] = $params;

//you may initialise the document object here and set the buffers
//$document = JFactory::getDocument();
//$document->setBuffer($contents, 'module', $name);
// $document->setHeadData($data['head']);etc

echo $doc->render(false, $options);
$app->close();

Of course dont expect it to display the same way esp if you use relative urls. Can be used for other purposes though like examining the scripts in a document template. tested on Joomla 3.3 PHP 5.5 . It will not work on lower versions like 1.5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM