I'm coding an app in PHP for school work and I'm using Twig template engine lonely (without a framework).
I got a file which initialize Twig in my project and I use it in all files that need it.
include_once('./Twig/lib/Twig/Autoloader.php');
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
'cache' => false,
'charset' => 'utf-8'
));
I have a Twig Function which returns the path to my static files folder. But when I run addFunction($my_function) I got the error below :
Warning: Missing argument 1 for {closure}()
My Twig function:
$url_for_static = new Twig_SimpleFunction('static_folder', function () {
$static_folder = "./static" ;
return $static_folder ;
});
$twig->addFunction($url_for_static);
I know this answer is really late but i finally found a solution to my problem. My Twig function declaration was wrong.
This worked for me :
`
function blank_space($size=100) {
echo "<div class='grid-". $size ." hidden'> <span> hidden </span> </div>" ;
}
$twig->addFunction('blank_space', new Twig_Function_Function('blank_space')) ;
`
I have never used Twig before, but it seems the closure is called with an argument but you didn't define any arguments in your closure. Try this:
$url_for_static = new Twig_SimpleFunction('static_folder', function ($arg) {
var_dump($arg);
$static_folder = "./static" ;
return $static_folder ;
});
I know this answer is really late but i finally found a solution to my problem. My Twig function declaration was wrong.
This worked for me :
function blank_space($size=100) {
echo "<div class='grid-". $size ." hidden'> <span> hidden </span> </div>" ;
}
$twig->addFunction('blank_space', new Twig_Function_Function('blank_space')) ;
Related
I use last version of Twig in Codeigniter project, I have an error I don't understand. I load my functions using Twig but I get this error :
Message: An exception has been thrown during the compilation of a
template ("Function () does not exist") in "base.twig".
To load my functions I use :
foreach(get_defined_functions() as $functions)
{
foreach($functions as $function)
{
$this->_twig->addFunction( new \Twig_Function($function) );
}
}
Then in template I try :
{{ base_url('test') }}
I made a var_dump of $twig->getFunctions(), and base_url() is listed.
I just migrated to the last version of Twig, and got this error.
Did I miss something ?
Ok I found the way in Twig 2.2.4 :
foreach(get_defined_functions() as $functions)
{
foreach($functions as $function)
{
$this->_twig->addFunction( new \Twig_SimpleFunction($function, $function) );
}
}
It works.
I am migrating from clean php views to smarty, and I have a problem converting the following template into smarty:
<?php
use \framework\core;
?>
<h1><?= Core::translate('some string to translate'); ?></h1>
So I want to use some class that's loaded via autoloader, and then use its translate method. How can I do that in smarty?
This is how I did this same task in one of my older projects using Smarty API extension:
// register additional smarty modifiers for I18N
$this->smarty->register_block("translate", array($this, "smarty_i18n_translate"));
// better alias
$this->smarty->register_block("_", array($this, "smarty_i18n_translate"));
// translation function
public function smarty_i18n_translate($params, $content, &$smarty, &$repeat)
{
if (isset($content))
{
if (isset($params['resourceID']))
{
$resourceID = $params['resourceID'];
unset($params['resourceID']);
}
else
$resourceID = NULL;
// setting context vars if specified
foreach ($params as $key => $val)
{
$this->setContextVar($key, $val);
}
// Core::translate($content); ?
return $this->translate($content, $resourceID);
}
return '';
}
This allows writing in views (I used {? as smarty tag delimiter):
<span class="label">{?_?}Operation type{?/_?}:</span>
One note: this was for some pretty ancient version of Smarty, they may have changed details of API, but it seems register methods are still there.
Btw in the docs there is this same problem illustrated as example: http://www.smarty.net/docsv2/en/api.register.block.tpl
try this logic/way, hope you might get some idea..
<?php
$my_obj = new MyClass();
$smarty->left_delimeter('{{');
$smarty->right_delimeter('}}');
$smarty->assign('my_obj', $my_obj);
$smarty->display('your.html');
?>
Then on your html
<h1>{{ $my_obj->translate('some string to translate'); }}</h1>
I'm writing a CodeIgniter library around PHP's bbcode PECL extension, but I'm having some trouble with callbacks.
I set up the handler in the library constructor:
function __construct() {
$basic = array(
'url' => array(
'type' => BBCODE_TYPE_OPTARG,
'open_tag' => '<a href="{PARAM}" rel="nofollow">',
'close_tag' => '</a>',
'childs'=>'i,b,u,strike,center,img',
'param_handling' => array($this, 'url')
)
);
$this->handler = bbcode_create($basic);
}
public function parse($bbcode_string) {
return bbcode_parse($this->handler, htmlentities($bbcode_string));
}
As you notice, this uses a callback for handling what's allowed to go into the URL. I use this to insert an "exit redirect" page
public static function url($content, $argument) {
if (!$argument) $argument = $content;
$url = parse_url($argument);
if (!isset($url['host'])) {
if (strlen($argument) > 0 && $argument[0] != '/') return false;
$destination = '//'.$_SERVER['HTTP_HOST'].$argument;
} elseif ($url['host'] != $_SERVER['HTTP_HOST']) {
$destination = '//'.$_SERVER['HTTP_HOST'].'/exit?'.urlencode($argument);
} else {
$destination = $argument;
}
return htmlspecialchars($destination);
}
And I also have a little function which helps me test this out as I work:
function test() {
$string = '[url]http://www.google.com[/url]';
echo '<pre>';
die($this->parse($string));
}
This all works fine if the test() method is called from within the library. For example, if I throw $this->test() at the bottom of the constructor, everything works exactly as I would expect. However, calling $this->bbcode->test() from somewhere else (e.g. in a controller), I get the following errors:
**A PHP Error was encountered**
Severity: Warning
Message: Invalid callback , no array or string given
Filename: libraries/bbcode.php
Line Number: 122
**A PHP Error was encountered**
Severity: Warning
Message: bbcode_parse(): function `' is not callable
Filename: libraries/bbcode.php
Line Number: 122
http://www.google.com
The callback does not get executed, and as a result the link's href attribute is empty. Line 122 refers to the single line of code in my parse function:
return bbcode_parse($this->handler, htmlentities($bbcode_string));
How do I address this callback function such that it can be located when $this->bbcode->test() is called from inside a controller?
Now I'm even more confused...
So in the hopes of just putting this all behind me, I put these callback functions in a helper so I can just call them directly. So I now have code like this:
function __construct() {
$basic = array(
'url' => array(
'type' => BBCODE_TYPE_OPTARG,
'open_tag' => '<a href="{PARAM}" rel="nofollow">',
'close_tag' => '</a>',
'childs'=>'i,b,u,strike,center,img',
'param_handling' => 'bbcode_url'
)
);
$this->handler = bbcode_create($basic);
}
With the above, I get the following error:
**A PHP Error was encountered**
Severity: Warning
Message: Invalid callback 6.7949295043945E-5, no array or string given
Filename: libraries/bbcode.php
Line Number: 176
**A PHP Error was encountered**
Severity: Warning
Message: bbcode_parse(): function `6.7949295043945E-5' is not callable
Filename: libraries/bbcode.php
Line Number: 176
(line 176 is the new location of the parse() function)
Um... I don't even know what's going on. The number 6.7949295043945E-5 changes with every attempt.
The only solution I have found to this is quite simply not to set the handler up in a constructor. Instead, the parse() method contains both the bbcode_create() call and the bbcode_parse() call. That is, the bbcode_handler is freshly created for every string of bbcode to be parsed.
This seems needlessly wasteful to me. But, over the course of the lifetime of this project, it is exceedingly unlikely to cost even a tenth of the amount of time that I have spent trying to sort this out "properly", so I'm calling it a day.
I'm posting this "solution" here in case somebody else happens across this question and can thereby save themselves a few hours' pain. That said, I would really like to know what on earth is going on, and how to do this properly.
I have been writing procedural php for years and am very comfortable with it. Recently I decided to rework an existing site and switch to PDO and OOP. Everyone is telling me that this is a better way to go but the learning curve is killing me. When trying to call a class, I get the following.
Menu Builder
vbls: 5 1
Notice: Undefined variable: Menu in /home/lance/DallyPost/projectWebSite/trunk/1/core/modules/menuBuilder.php on line 9
Fatal error: Call to a member function menuFramework() on a non-object in /home/lance/DallyPost/projectWebSite/trunk/1/core/modules/menuBuilder.php on line 9
The procedure is that I have included menu.php at the top of index.php, prior to including the following script:
<?php
//menuBuilder.php
echo"<h2>$pageTitle</h2>";
$pub = $_URI_KEY['PUB'];
$dir = $_URI_KEY['DIRECTORY'];
echo"vbls: $pub $dir";
if($Menu->menuFramework("$pub", "$dir") === false) {
echo"The base menu framework failed to build correctly.";
}
else{
echo"<p>The base menu framework has been successfully constructed.</p>";
}
?>
As you can see, the above script calls a method in the Menu class:
<?php
//menu.php
class Menu{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function menuFramework($pub, $directory){
$link = "/" . $directory . "/index.php/" . $pub . "/home/0/Home-Page/";
$inc = "core/menus/" . $pub . "category.php";
$file = "core/menus/" . $pub . "menuFramework.php";
$text = "<nav class=\"top-bar\" data-topbar>";
$text .= "<ul class=\"title-area\">";
$text .= "<li class=\"name\">";
$text .= "<h1>Home Page</h1>";
$text .= "</li>";
$text .= "</ul>";
$text .= "include($inc)";
$text .= "</nav>";
//write text to a file
if(file_put_contents($file, $text)){
return true;
}
else{
return false;
}
}
... rest of file not shown
Can you help me understand why I am getting this error. My understanding is that the variable was or should have been defined when I included menu.php, which was done before which was called a the top if index.php
Thanks
add this at the top of the script
$menu = new Menu($dbHandle);
That's not how classes work. You can't reference an entire class, Menu, with a variable, $Menu, to invoke instance methods.
You need to create an instance of your class on which to invoke methods:
$menu = new Menu(...);
You can create class-level "static" methods which are invoked on the class itself, but that syntax doesn't involve $Menu. You would use Menu::method_name() for that.
You are calling $Menu->
so your are a calling a variable called Menu, instead of the class Menu.
anyways, that function is not static, so you need to instantiate an object.
For that, add a this line:
$menu = new Menu($db);
where $db is your database object, if you really need it, or null if you dont (i cannot say with that code fragment)
and then call
$menu->menuFramework(...)
I use symfony 1.4.8 , and sfBBCodeParserPlugin
It works , but I have problem with partial.
My IndexSuccess
include_partial('post/list', array('voice_posts' => $voice_posts)) ?>
In _list.php
echo $bb_parser->getRawValue()->qparse($voice_post->getDescription());
And I have error
Notice: Undefined variable: bb_parser in...
according to the readme I added in action.class
public function executeIndex(sfWebRequest $request)
{
....
$this->bb_parser = new sfBBCodeParser();
}
In ShowSuccess I do not use partial and all work fine.
ShowSuccess.php
echo $bb_parser->getRawValue()->qparse($voice_post->getDescription())
action.class
public function executeShow(sfWebRequest $request)
{
$this->bb_parser = new sfBBCodeParser();
...
}
p.s Sorry for my bad English
You forget you send to the partial the bb_parser:
include_partial('post/list', array('voice_posts' => $voice_posts, 'bb_parser' => $bb_parser))
Remember that the variables used in partials (unless they're global) must be sent when you're defining it.