Opencart 3 extending Twig (access Twig environment from a controller) - twig

In Opencart 3, is there a way to access twig environment from a controller?
working with OC v3.0.3.1
I am trying to add a custom function which I could use in the template.
I am using the documentation here
Tried adding the following to the controller:
$loader = new \Twig_Loader_Filesystem(DIR_TEMPLATE);
$config = array('autoescape' => false);
$twig = new \Twig_Environment($loader, $config);
$function= new \Twig_SimpleFunction('foo', function(){
return 'bar';
});
$twig->addFunction($function);
in the template I have:
{{ foo() }}
Getting:
Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'Unknown "foo" function in ...

Related

PHP __LINE__ equivalent for twig

There is a way to get PHP __LINE__ equivalent for Twig?
It's almost impossible to search __LINE__ on Google as exact word...
The purpose is purely for debugging a long twig file containing nested twig code inside a complex Js code, to console.log it.
The version of twig I'm using is 2.12.5.
Thanks
First things first:
As seen in the PHP documentation the (magic) constant will return the current line number of the file.The "problem" here is that twig converts templates to PHP in order to render them.
This means if you were actually were to be able to use __LINE__ inside a template, it would report back the line number from either a temporary PHP file or a cached PHP file, wether you have caching enabled or not.
TLDR: Using __LINE__ inside a template is going to report back "false"/useless information.
However, you can easily extend twig and even introduce new tags which you then can use inside templates. These customs tags allow you to modify/alter the compilation of the template's PHP file.
The interesting part here is that the "compiler" is able to provide your custom tag on which specific line the tag was called.
We can even create a custom tag, register it with twig and let the tag report back the line number in the parsed template.
Step 1 - Create a TokenParser
The TokenParser is responsible for parsing the template and allows you to choose a name for your tag. The code below will be responsible to create a simple, empty tag named line
<?php
namespace MyProject\Base\Twig\TokenParser;
use \MyProject\Base\Twig\Node\Line as LineNode;
class Line extends \Twig_TokenParser {
public function parse(\Twig_Token $token)
{
$this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
return new LineNode(new \Twig_Node(), $token->getLine(), $this->getTag());
}
public function getTag()
{
return 'line';
}
}
Step 2 - Create a Node
The Node is responsible for converting the template code to actual PHP code
<?php
namespace MyProject\Base\Twig\Node;
class Line extends \Twig_Node {
public function __construct(\Twig_NodeInterface $body, $lineno, $tag = null) {
parent::__construct(['body' => $body,], array(), $lineno, $tag);
}
public function compile(\Twig_Compiler $compiler) {
$compiler->write('echo '.$this->getLine().';')
->write(PHP_EOL);
}
}
Step 3 - Register the tag with twig
<?php
namespace MyProject\Base\Twig;
class MyProjectTwigExtension extends Twig_Extension {
public function getTokenParsers() {
return [
new \CMS4U\Base\Twig\TokenParser\Line(),
];
}
public function getName() {
return 'MyProjectTwigExtension';
}
}
<?php
$twig->addExtension(new \MyProject\Base\Twig\MyProjectTwigExtension());
If everything is good, you can now use the custom tag {% line %} wherever you like in any template
Foo
Bar
FooBar
Current line number is {% line %} {# 4 #}

Puppet - undefined local variable

I'm getting undefined error but it is defined already. I'm sure this was working before (maybe in puppet 3) but I'm trying to use that code on puppet 6 (on a new server).
Any idea what is the issue? Here is the error code:
Error: Error while evaluating a Function Call, Failed to parse template resolv/resolv.conf.erb:\n
Filepath: /etc/puppetlabs/puppet/modules/resolv/templates/resolv.conf.erb\n Line: 1\n
Detail: undefined local variable or method `domain' for #<Puppet::Parser::TemplateWrapper:0x60d6ba83>\n
Here is the code:
class resolv {
case $hostname {
/^[Abc]/: {
resolv:resolv_config { 'Default':
domain => "mydomain.local",
}
}
}
}
define resolv::resolv_config($domain){
file { '/etc/resolv.conf':
content => template("resolv/resolv.conf.erb"),
}
}
Here is the template content:
cat resolv.conf.erb
domain <%= domain %>
Figured it out.
All Puppet variables need to be prefixed with # in Puppet 4+
So resolv.conf.erb should look like
domain <%= #domain %>

Dompdf in services not found; Controller error "Message: Class 'Dompdf' not found"

I am working with symphony and slim, so I use services that can be called in my controllers, then to my twig views. I installed Dompdf with composer and added it to my list of services I my bootstrap folder. I have tried several ways to call dompdf, but still get
Message: Class 'Dompdf' not found
This is the code in my controller:
class SlipController extends \App\Controllers\Base\PageController{
function getHandler($request, $response, $args)
{
// Instantiate Dompdf with our options
$dompdf = new Dompdf();
$dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser (force download)
$dompdf->stream("mypdf.pdf", [
"Attachment" => true
]);
return $this->view->render($response,'pages/slips.twig');
}
In the services.php
<?php
$container['dompdf'] = function($container) {
return new \Dompdf\Dompdf;
};
Did you add a use statement to your code?
use Dompdf\Dompdf;
class SlipController extends \App\Controllers\Base\PageController{
function getHandler($request, $response, $args)
{
...

Error in setting up Twig with CodeIgniter

I am trying to set up Twig Templating Engine with my new Codeigniter project.
But I am getting this error after setting up
Twig Exception
There are no registered paths for namespace "__main__".
I don't know what this error means. and how to solve it.
As per I am checking this is originated from the following file-
/application/vendor/twig/twig/lib/Twig/Loader/Filesystem.php:
code:
class Twig_Loader_Filesystem implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface
{
/** Identifier of the main namespace. */
const MAIN_NAMESPACE = '__main__';
protected $paths = array();
protected $cache = array();
protected $errorCache = array();
private $rootPath;
...
I followed this article for setting up
https://github.com/bcit-ci/CodeIgniter/wiki/Twig-PHP-Template-Engine-Implementation
Codeigniter Version- 3.1.8
Finally I made it.
I was missing this entry in autoload.php file
$autoload['config'] = array('twig');

Twig and error messages - is this normal?

I've been testing Twig on localhost... the code here is the same as in this question but the query is different:
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'mypass');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT manufacturer, model, modelinfo FROM automobiles WHERE id = '4' ";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('cars.html');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
I have 3 records; I decided to query a non-existent record to see what Twig's error handling was like, as I was comparing Twig vs Smarty - out of interest, and for a project.
This error message comes up:
Notice: Undefined variable: data in /Applications/MAMP/htdocs/mysite/twigtesting.php on line 42
Surely a notice saying 'Data not found' should happen or am I wrong here?
Undefined variable data refers to:
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
Why is this happening? I'm new to Twig, and using the latest build from their site, f that's relevant.
You don't get a Twig error, because the error does not exists in the templates, but in the code that is generating these templates.
PHP is having issues to put the value of $data inside an array, because that variable does not exists.
If you want to see how twig handles errors, you need to access a non existing variable inside a template. For instance, putting {{ notExisting }} in your current template.
I can already say that Twig is handling errors by throwing parsing exceptions in PHP. All exceptions thrown by Twig are extending Twig_Error. To catch these, use a try { ... } catch (\Twig_Error $e) { ... } block.
Furthermore, Twig can throw 3 different types of Exceptions:
Twig_Error_Syntax is thrown when an error occurs when parsing a template (e.g. using malformed tags).
Twig_Error_Loader is thrown when Twig can't load a file. This can happen when using a render() method, or when you use some file features in Twig (e.g. {% extends ... %}).
Twig_Error_RunTime is thrown when an error occurs in runtime (e.g. an error inside extensions).

Resources