Coder Social home page Coder Social logo

raintpl3's Introduction

RainTPL 3

By Federico Ulfo and a lot awesome contributors!

RainTPL is an easy template engine for PHP that enables designers and developers to work better together, it loads HTML template to separate the presentation from the logic.

Features

  • Easy for designers, only 10 tags, {$variable}, {#constant#}, {include}, {loop}, {if}, { comment }, {noparse}, {function}
  • Easy for developers, 5 methods to load and draw templates.
  • Powerful, modifier and operation with variables
  • Extensible, load plugins and register new tags
  • Secure, sandbox with blacklist.

Installation / Usage

  1. Install composer https://github.com/composer/composer

  2. Create a composer.json inside your application folder:

    {
        "require": {
            "rain/raintpl": ">=3.0.0"
        }
    }
  3. Run the following code

    $ php composer.phar install
  4. Run one example of RainTPL with your browser: http://localhost/raintpl3/example.php

Documentation

The documentation of RainTPL is divided in documentation for web designers and documentation for PHP developers.

Licence

RainTPL 3, like its antecessor Rain.TPL version 2, is, as of 2018-06-07, published under the MIT Licence.

The above applies to RainTPL 3 itself, not the entire content of this repository. Some of the example-*.php files and the content below templates/ in this repository are copies of external code under various licences, such as:

  • Twitter Bootstrap, under the Apache v2 licence
  • LESS - Leaner CSS, under the Apache v2 licence

Note that not all external content comes with full source code, it’s usually just a copy of (possibly minified or otherwise modified) parts of their distribution. The example files may be used as starting points without limitation except the licences on the external content.

raintpl3's People

Contributors

amunhoz avatar aseba avatar aspyatkin avatar barrydam avatar faryshta avatar feulf avatar gamma613 avatar jnerin avatar kargnas avatar manawyrm avatar mirabilos avatar pmickael avatar smsaladi avatar suralc avatar wu3rstle avatar xpaw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

raintpl3's Issues

htmlspecialchars should specify a charset

Actually in RainTPL3, htmlspecialchars is called like this:

$html = "htmlspecialchars( $html )";

But by default htmlspecialchars uses the ISO-8859-1 charset. And personnally I prefer to use UTF-8, so you should add a config option so that we can choose the charset (and make it default to UTF-8?), like this:

protected static $charset = 'UTF-8';
(...)
$html = 'htmlspecialchars('.$html.', ENT_COMPAT, ''.self::$charset.'', false)';

The regex for A href replace does not work

The first item in the regex did not find anything... so it put the base link in all links.

$exp = array_merge( $exp , array( '/<a(.?)href=(?:")(http://|https://|javascript:|mailto:)([^"]+?)(?:")/i', '/<a(.?)href="(.?)"/', '/<a(.?)href=(?:@)([^"]+?)(?:@)/i' ) );
$sub = array_merge( $sub , array( '<a$1href=@$2$3@', '<a$1href="' . $context->conf['base_url'] . '$2"', '<a$1href="$2"' ) );

New features

Hi... first, i love Raintpl! Thanks everybody!

Second, i missed tags for break and continue inside the loops.
I´ve made a small modification for myself, however it should be nice to be integrated in the main code.

Third, can a template variable be passed as a parameter of a registered tag? I would be awesome!

Thanks
Alexandre

Documentation on github page

It could be nice to start writing a new documentation for RainTPL 3.0 directly here in github, with the github pages, so that everyone can contribute to it.

Anyone of you guys has experience and time to start writing it?

Ternary operator parses incorrect things

I had twitter's widget script code included in one of my templates, and it parsed it as a ternary operator

Here's the code:
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','twitter-wjs');</script>

I'm not sure what was the point of including a ternary operator, when the same thing could be accomplished with if statements and with less hassle to support.

{include="$page"} with subfolder // BUG

index.php
$tpl->assign(array('page'=>'result_add'));
$tpl->draw('admin/layout');

admin/layout.html
{include="$page"}

cache/layout.*.rtpl.php

checkTemplate(admin/htmlspecialchars( $page, ENT_COMPAT, 'CP1251', FALSE ));?>

Feature Request: Fluent Interface and Factory

Hi, I've found rainTPL a few days ago and have to say: I like what it's all about!
But I have one small feature request: Could you build in the fluent-interface and a factory method?

All you have to do is to return $this at the end of each setter (like "assign()", "configure()", "clean()", "register_tag()", ...). Then it's possible to build code that looks like this:

raintpl::factory('template', 86400) // template name and expire-time (both optional).
    ->assign("name", $name)
    ->assign("name2", $name2)
    ->draw("my_template");

The factory method is just an static method, which looks something like this:

public static factory($name='', $expire=null) {
    $instance = new raintpl;
    $instance
        ->set_template($name) // Method to set the template name.
        ->set_expiration($expire); // Method to set the expiration-time.
    return $instance;
}

I hope you like the idea, if you like I can send you a pull request the next days!

P.S.: Sorry for the "issue"

syntax error, unexpected '['

Why this
{if="$render_time > 1.0"}important{/if}

is compiled into this
$render_time > 1["0"]

Where did that array come from? It's working fine with version 2.

Bug: blacklist matches are invalid

Hi. I recently noticed that string {function="localize('Informations about system', 'settings')"} is raising an Exception "Syntax system', ' not allowed in template".

But i not used system command, i just used my custom string translation function.
I had to turn off sandbox mode.

Non relative paths...

Right now i'm using in situations where i can't use relative paths...
In this case, the current version of raintpl does not deal good with that.
Where i use:
conf['tpl_dir'] = "/dir/tpl"
It can't find the template.

I've made some changes to work with, however that´s not the best solution.
Any ideas to make it better?

Static functions via template

I can't seem to access static functions via the template.

Example:

example-2.php

<?php

    // namespace
    use Rain\Tpl;

     class Test {
        function test() {
            echo 'x';
        }
     }

    // include
    include "library/Rain/Tpl.php";

test.html

    Variable as key {$week[$numbers.0]} <br><br>
    Var test {$variable} <br><br>
    Testing staic class {function="Test::test()"}<br><br>

output:

Variable as key Thursday

Var test Hello World!

Testing static class {function="Test::test()"}

{loop} sanity checks

In the compiled code, {loop} tag produces pretty big if() with lots of checks to make sure that variable can be looped though. I think that these checks are unnecessary. It should be up to the developer to make sure it's an correct array (just like any other tag, where checks like that are not performed). I already removed that extra if() from my website, and it works just like I expect it to.

loop bug

Code1

{loop="$array" as $myKey => $name}
    {$myKey|var_dump}
{/loop}

Result1

0
1

Code2

{loop="$array" as $name}
    {$key|var_dump}
{/loop}

Result2

0
1

Code3

{loop="$array" as $key => $name}
    {$key|var_dump}
{/loop}

Result3

NULL
NULL

Result3 should be same as other results.

Why lock the file when reading

In compileFile, you are opening the file for reading and then locking it. I think file_get_contents would do the job just fine.

Security concerns

Right now i'm using raintpl inside my frontend and backend, and i was thinking about security issues.

Since the cache folder usually have writing permission, it can be possible to change the php code inside it and make a mess, bypassing the blacklist from raintpl.

So, i was considering to make a plugin wich maintain a file inside cache dir with a encrypted hash of each php, checking it before run.

Do think this is the best solution? Anything else besides taking off the writing permission?

loop bug - Using {$key} on sub template in loop

Parent Template

{loop="$array" as $stats} // temp solution: as $newKey => $stats
    {include="stat"}
{/loop}

Stat Template

{$key} {$stats->hp} {$stats->mp} {$stats->power}

{$key} will print nothing.

RegEx for _var_replace

on line 619:
if( preg_match_all('/($[a-z_A-Z][.[]"'a-zA-Z_0-9]*)/', $html, $matches ) ){

should be replaced with:

if(preg_match_all('/($[a-z_A-Z][.[]"'a-zA-Z_->0-9]*)/', $html, $matches)){

this way templates like : $obj->prop.array_key can work properly.

Not tested on 100% but i think it should be ok.

Inconsistent use of visibilitymodifiers

I just had a quick overview over the raintpl3 source and noticed that the php5 visibility modifiers are used in an inconsistent way. The methods declared in the Exception classes have them, while the core class omits them.

I think, they should be added to the core class, because of readability and consistency. Also there are some "protected static" and "static protected" methods, which is very annoying to read.

Also RainTPL::_compileTemplate uses $this in line 251, but is called in static context in line 158 in RainTPL::compileFile.

Could look simliar to this: https://github.com/suralc/raintpl3/commit/e8da19e560048878b5ac7f6334f946cc990740f4

Minify compiled code

It would be great if compile code (inside temp folder) would be without any tabs, spaces and comments.

Trouble extending RainTPL

RainTPL makes extensive use of static methods and the self-keyword. This lets you run into some unexpected trouble if you want to extend raintpl and implement a singe selfwritten method. So you either have to implement all methods using your method, or hack yourself into the core-code.

Having non-static methods or the use of the static-keyword(php 5.3++) would prevent this.

To illustrate this:

<?php
class A {
    protected static $var = 'test';
    public  static function selfMethod(){
        return self::what();
    }
    public static function  staticMethod(){
        return static::what();
    }

    public static function what(){
        return 'Called in A';
    }

    public static function get(){
        return self::$var;
    }
}

class B extends A{
    protected static $var = 'something different';
    public static function what(){
        return 'Called in B';
    }
}

var_dump(B::selfMethod()); // Called in A
var_dump(B::staticMethod()); // Called in B
var_dump(B::get()); // test

The same goes for CLASS if it is called inside a static method. It returns the class it was defined by, and not the one in which it was called.

If wanted I`ll ad a patch later this day.

Unnecessary $counter?

I noticed it added $counter1=-1; in compiled template, and was incrementing it inside the loop, and that was it. Looking at the library, I can't find where it is used either. Could it be safely removed?

Error - Undefined variable context

Hi there,

I have an error when I'm trying to use RainTPL3. I'm using WAMP, and I installed manually the script (can't use Composer at work..).

I have this error : Notice: Undefined variable: context in C:\wamp\www\template\library\Rain\Tpl.php on line 125.

In the Tpl.php code, this is :

public function draw($templateFilePath, $toString = FALSE) {
    extract($this->var);
    // Merge local and static configurations
    $this->config = $this->objectConf + static::$conf;
    $this->getPlugins()->run('beforeDraw', $context);    // ERROR HERE ($context)
    ...
}

Here is my code :

require 'library/Rain/autoload.php';

use Rain\Tpl;


$config = array(
    'tpl_dir'   => 'includes/templates/test/',
    'cache_dir' => 'includes/cache/'
);

Tpl::configure( $config );

// Add PathReplace plugin (necessary to load the CSS with path replace)
//Tpl::registerPlugin( new Tpl\Plugin\PathReplace() );


// Variables
$title = 'Page de test !';
$jours = array(
    'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'
);


$tpl = new Tpl;
$tpl->assign( 'title', $title );
$tpl->assign( 'jours', $jours );
$tpl->draw( 'test' );

Thanks

{$a * 1000|round} compiles incorrectly

In previous version it was parsed to <?php echo round($a* 1000); ?>, but now it's <?php echo $a* Round(1000); ?>.

Is it supposed to work like that now?

Include with local variables feature

{include "file.tpl" $var="1"}

This will works in smarty. As $var is local variable. It can be migrated to raintpl like this:

{$var="1"}
{include="file"}

But this will occur a problem like this:
Smarty
$smarty->assign('user', User::myInstance('myidentifier'));

{foreach $users as $key => $userItem}
    user{$key}: {include "userIdentnfier.tpl" user=$userItem}
{/loop}
myId: {$user->identifier()}

Result

user0: tom
user1: jerry
user2: mike
myId: myidentifier

Raintpl3
$raintpl->assign('user', User::myInstance('myidentifier'));

{loop="$users" as $userItem}
    {$user=$userItem}
    user{$key}: {include="userIdentnfier.tpl"}
{/loop}
myId: {$user->identifier()}

Result

user0: tom
user1: jerry
user2: mike
myId: mike

This feature is not awesome(easy to bypass), but so useful to clean code. Don't need to raintpl now, but can be enhanced in future.

[Question] - Replacing in string

Hi there,

I'm trying to use RainTPL3 without using a template, but I'm not sure it lets user to do it.

That's my case :

  • I have a string with some variables to replace
  • I have a template with some variables to replace (and the string below is included in)

So, I need to replace all variables in a string which will be used to convert a variable in the template. Is there a way to do that with RainTPL, or must I use str_replace (for example) ?

Thanks

Possibly optimize usage of php brackets

{if="!isset( $current_page )"}{$current_page = ''}{/if}
gets compiled to
<?php if( !isset( $current_page ) ){ ?><?php $current_page = ''; ?><?php } ?>
which makes sense, but it would make even more sense if it was compiled to
<?php if( !isset( $current_page ) ) { $current_page = ''; } ?>

Cssless and Minify

I´ve managed to integrate these applications in Raintpl (cssless and minify)...
However... i´m working in a hybrid version of old 2.0 with 3.0. I do preffer the "one file" mode of it.

I´ve done it with 3 new tags {cssless="/file.css"}, {minify="/file.css"} and {csslessmin="/file.css"} putting new tags in raintpl main code.

It creates a new css file inside a temp directory and replace the tag with the new link, it can be used with more than one file or with JS files (minify).

Perhaps it can be done with the plugin system, but it will not be so optimized as inside the main tag verification.

So... for me it´s been really useful. But, right now, i dont think i can help that much with the main raintpl3 code. I can send you some chunks of my code to help.

Possibly optimize checkTemplate function

I feel like this function could be optimized quite a bit by caching some variables, and not re-calculating them every time the function is called. checkTemplate is always called regardless of cache, and if you have a lot of {include}'s in your code, it's called multiple times.

What do you think?

Multiple template directory.

What about this feature to the philosophy of Rain?
In smarty, I did use this feature for mobile. (But there are some bugs.)

RainJS for Ajax?

I can't use rainTPL template files with client side with ajax. Does RainJS template engine on the way or anyway to use its templates with js ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.