I have one array for data
$data = array(title=>'some title', date=>1350498600, story=>'Some story');
I have a template
$template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#";
All i want is to fit data into template and i know that can be done by str_replace but my problem is the date format. date format is coming from the template not from the data, in data date is stored as php date.
yesterday i tried to ask the same question but i think my question wasn't clear.
Anybody please help me.
i think it won't work with str_replace easily so i'm going to use preg_replace
$data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
$template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#";
$result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', function ($match) use($data) {
$value = isset($data[$match[1]]) ? $data[$match[1]] : null;
if (!$value) {
// undefined variable in template throw exception or something ...
}
if (! empty($match[2]) && $match[1] == "date") {
$value = date($match[2], $value);
}
return $value;
}, $template);
Instead of using date(m) or date(Y) you could also do things like
date(d-m-Y) using this snippet
This has the disadvantage that you can format only the date variable using this mechanism. But with a few tweaks you can extend this functionality.
Note: If you use a PHP version below 5.3 you can't use closures but you can do the following:
function replace_callback_variables($match) {
global $data; // this is ugly
// same code as above:
$value = isset($data[$match[1]]) ? $data[$match[1]] : null;
if (!$value) {
// undefined variable in template throw exception or something ...
}
if (! empty($match[2]) && $match[1] == "date") {
$value = date($match[2], $value);
}
return $value;
}
$data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
$template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#";
// pass the function name as string to preg_replace_callback
$result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', 'replace_callback_variables', $template);
You can find more information about callbacks in PHP here
I'd suggest using a templating engine like so:
https://github.com/cybershade/CSCMS/blob/master/core/classes/class.template.php
And then your templates turn out like this:
https://github.com/cybershade/CSCMS/blob/master/themes/cybershade/site_header.tpl
and
https://github.com/cybershade/CSCMS/blob/master/modules/forum/views/viewIndex/default.tpl
Download this file: http://www.imleeds.com/template.class.txt
Rename the extension to .PHP from .TXT
This is something I created years ago, I keep my HTML away from my PHP, always. So see an example below.
<?php
include("template.class.php");
//Initialise the template class.
$tmpl = new template;
$name = "Richard";
$person = array("Name" => "Richard", "Domain" => "imleeds.com");
/*
On index.html, you can now use: %var.name|Default if not found% and also, extend further, %var.person.Name|Default%
*/
//Output the HTML.
echo $tmpl->run(file_get_contents("html/index.html"));
?>
Related
I have a simple template engine that works fine the simple template, but I don't know how to adapt it to make it work with loops :
class Template {
public $template;
function getFile($file) {
$this->template = file_get_contents($file);
}
function set($tag, $content) {
$this->template = str_replace("{".$tag."}", $content, $this->template);
}
function ouput() {
eval("?>".$this->template."<?");
}
}
That's the loop I want to parse and display:
{{#each Stuff}}
{{Thing}} are {{Desc}}
{{/each}}
I dont want use any SMARTY or Twig engine.
Any idea please?
Ok, keep in mind this is just for learning purposes. You can't ask on SO for the whole code, you need to try and post question about your tries.
This code parse a string for a foreach and then executes it:
<?php
$var = array(2, 4);
$str = 'for i in var';
$a = explode(' ', $str);
foreach (${$a[3]} as $i => $value)
{
echo $value;
}
Read this part from PHP docs to understand what i did.
I am currently trying to create a simple template engine in PHP. The main thing I care about is security, however template tutorials do not. Lets say I have a database table with a username and his description. The user can type whatever he wants there.
My guess would be to use htmlspecialchars() function, to prevent javascript and html injection. But what about 'template code injection'? If my template rule is to replace [#key] to "value", the user can update his description that interferes with my template handler. Should I treat "[", "#", "]" as special characters and replace them with their ascii code when using my set method?
template.php:
class Template {
protected $file;
protected $values = array();
public function __construct($file) {
$this->file = $file;
}
public function set($key, $value) {
$this->values[$key] = $value;
}
public function output() {
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[#$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
}
example.tpl:
Username: [#name]
About me: [#info]
index.php:
include 'template.php';
$page = new Template('example.tpl');
$page->set('info', '[#name][#name][#name]I just injected some code.');
$page->set('name', 'Tom');
echo $page->output();
This would display:
Username: Tom
About me: TomTomTomI just injected some code.
The code I used is based on:
http://www.broculos.net/2008/03/how-to-make-simple-html-template-engine.html
Change your function to search in the unchanged template only once for the known keys:
public function output() {
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).";
}
$output = file_get_contents($this->file);
$keys = array_keys($this->values);
$pattern = '$\[#(' . implode('|', array_map('preg_quote', $keys)) . ')\]$';
$output = preg_replace_callback($pattern, function($match) {
return $this->values[$match[1]];
}, $output);
return $output;
}
I was thinking about it and I think this solution is fastest and simplest:
foreach ($this->values as $key => $value) {
$tagToReplace = "[#$key]";
if (strpos($output, "[#$value]") !== FALSE)
$value = '['.substr($value,1,-1).']';
$output = str_replace($tagToReplace, $value, $output);
}
It replaces brackets in value with html entity string if [$value] is in output.
Used this html entity list
For future adopters:
This kind of solution is OK if Template Parser is implemented by loading non-interpeted/non-evaled file (as is OP's case by loading local file using file_get_contents). However, if it's implemented by INCLUDING PHP view, beware that this check won't handle the case when you put some user-modifiable data from database into view directly (without using parser, e.g. <?=$var;?>) and then use template parser for this view. In that case, parser has no way to know if these data are part of template structure and this check won't work for them. (I don't know how should this case be handled properly.) Anyhow, I think best practice is to never pass sensitive data to template parser, even if you don't use them in your template. When attacker then tricks parser to eval his custom data, he won't get information he didn't already have. Even better, don't use template parser.
How do I remove the auto label wrapping that is for the lang() in Codeigniter.
The manual doesn't say anything about it: https://www.codeigniter.com/user_guide/helpers/language_helper.html
Do I have to write a function by myself or is there a simple clean way that Im missing?
Don't write the second parameter. Keep it empty.
Take a look at the lang function (found in: /system/helpers/language_helper.php):
function lang($line, $for = '', $attributes = array())
{
$CI =& get_instance();
$line = $CI->lang->line($line);
if ($for !== '')
{
$line = '<label for="'.$for.'"'._stringify_attributes($attributes).'>'.$line.'</label>';
}
return $line;
}
As you can see it takes 3 parameters. The first parameter is required, but the second two are optional. If you state a second parameter it will return the language string wrapped in a label.
So stating only the first parameter should make it output just the language string.
UPDATE:
From reading your comment it sounds like you would be better off using the language class directly. However the language class alone will not be enough, you will need to extend it for your purpose. To do this you can create a new file in your application/core folder called MY_lang.php.
class MY_Lang extends CI_Lang {
// You want to extend the line function
function line($line = '', $value = '')
{
$line = ($line == '' OR ! isset($this->language[$line])) ? FALSE : $this->language[$line];
// We can assume that if a value is passed it is intended to be inserted into the language string
if($value) {
$line = sprintf($line, $value);
}
// Because killer robots like unicorns!
if ($line === FALSE)
{
log_message('error', 'Could not find the language line "'.$line.'"');
}
return $line ;
}
}
Assuming your language file has a string like so:
$lang['welcome_text'] = "Welcome %s";
You could then use this by loading the language class, and using the following code:
$name = "foo";
$this->lang->line('welcome_text', $name);
The above is 100% untested, so it may need some tweeking, but it should give you somewhere to start from.
I want to apply addslashes() to all the post elements got through
$this->input->post('my_var');
How can I do that ? Is there any feature like filters under wordpress for this ?
I think you want something global. My idea is to edit the global post function in the codeigniter to use addslashes on everything. You can find that function in:
/yourfolder/system/core/Input.php
You can escape it by setting it global.
function post($index = NULL, $xss_clean = FALSE)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();
// Loop through the full _POST array and return it
foreach (array_keys($_POST) as $key)
{
$post[$key] = addslashes($this->_fetch_from_array($_POST, $key, $xss_clean));
}
return $post;
}
return addslashes($this->_fetch_from_array($_POST, $index, $xss_clean));
}
Although I don't really find it as good solution to modify the global functions this should do the trick in your case.
Edit: I see that input->post already does that and you would not need to add that function additionally.
I need to make a small and simple php template engine I searched a lot and many of them were too complex to understand and I don't want to use smarty and other similar engines, I have got some idea from Stack Overflow like this:
$template = file_get_contents('file.html');
$array = array('var1' => 'value',
'txt' => 'text');
foreach($array as $key => $value)
{
$template = str_replace('{'.$key.'}', $value, $template);
}
echo $template;
Now instead of echo the template I just want to add include "file.html" and it will display the file with correct variable values and I want to put the engine in a separate place and just include it in the template what I want to use it declare the array and at the end include the html file like phpbb. Sorry I am asking to much but can anyone just explain the basic concept behind this?
EDIT: Well let me be frank i am making a forum script and i have got tons of ideas for it but i want make its template system like phpbb so i need a separate template engine custom one if you can help then please you are invited to work with me. sorry for the ad.. :p
file.html:
<html>
<body>
<h3>Hi there, <?php echo $name ?></h3>
</body>
</html>
file.php:
<?php
$name = "Keshav";
include('file.html');
?>
Doesn't get simpler than this. Yes, it uses global variables, but if simple is the name of the game, this is it. Simply visit 'http://example.com/file.php' and off you go.
Now, if you want the user to see 'file.html' in the browser's address bar, you'd have to configure your webserver to treat .html files as PHP scripts, which is a little more complicated, but definitely doable. Once that's done, you can combine both files into a single one:
file.html:
<?php
$name = "Keshav";
?>
<html>
<body>
<h3>Hi there, <?php echo $name ?></h3>
</body>
</html>
What if, for a script easier to maintain, you move those to functions?
something like this:
<?php
function get_content($file, $data)
{
$template = file_get_contents($file);
foreach($data as $key => $value)
{
$template = str_replace('{'.$key.'}', $value, $template);
}
return $template;
}
And you can use it this way:
<?php
$file = '/path/to/your/file.php';
$data = = array('var1' => 'value',
'txt' => 'text');
echo get_content($file, $data);
Once you iron out all bugs, fix huge performance problem you're getting yourself into, you'll end up with template engine just like Smarty and otheres.
Such find'n'replace approach is much slower than compilation to PHP. It does not handle escaping very well (you'll run into XSS problems). It will be quite difficult to add conditions and loops, and you will need them sooner or later.
<?php
class view {
private $file;
private $vars = array();
public function __construct($file) {
$this->file = $file;
}
public function __set($key, $val) {
$this->vars[$key] = $val;
}
public function __get($key, $val) {
return (isset($this->vars[$key])) ? $this->vars[$key] : null;
}
public function render() {
//start output buffering (so we can return the content)
ob_start();
//bring all variables into "local" variables using "variable variable names"
foreach($this->vars as $k => $v) {
$$k = $v;
}
//include view
include($this->file);
$str = ob_get_contents();//get teh entire view.
ob_end_clean();//stop output buffering
return $str;
}
}
Here's how to use it:
<?php
$view = new view('userprofile.php');
$view->name = 'Afflicto';
$view->bio = "I'm a geek.";
echo $view->render();