GithubHelp home page GithubHelp logo

eftec / bladeone Goto Github PK

View Code? Open in Web Editor NEW
737.0 22.0 110.0 1.1 MB

The standalone version Blade Template Engine without Laravel in a single php file and without dependencies

Home Page: https://www.escuelainformatica.cl/

License: Other

PHP 97.10% Blade 2.90%
template-engine blade-template php standalone laravel loop view

bladeone's Introduction

Logo

BladeOne Blade Template Engine

BladeOne is a standalone version of Blade Template Engine that uses a single PHP file and can be ported and used in different projects. It allows you to use blade template outside Laravel.

Packagist Total Downloads Maintenance composer php php php CocoaPods

Dynamic blade components are not supported (reason: performance purpose) and custom features aimed for blade, but everything else is supported.

Comparison with Twig

(spoiler) Twig is slower. 😊

First Time Time First Time Memory Overload First Time Second Time Second Time Memory
BladeOne 1962ms 2024kb 263 1917ms 2024kb
Twig 3734ms 2564kb 123 3604ms 2327kb

What it was tested?. It was tested two features (that are the most used): It was tested with an array with 1000 elements and tested many times.

Comparison with Twig

NOTE about questions, reports, doubts or suggesting:

✔ If you want to open an inquiry, do you have a doubt, or you find a bug, then you could open an ISSUE.
Please, don't email me (or send me PM) directly for question or reports.
Also, if you want to reopen a report, then you are open to do that.
I will try to answer all and every one of the question (in my limited time).

Some example

ExampleTicketPHP Example cupcakes Example Search Example Editable Grid
example php bladeone example php bladeone cupcakes example php bladeone search example php bladeone search
Custom control #1 Custom control #2
https://www.southprojects.com

Manual

PHP 5.x support?

This version does not support PHP 5.x anymore. However, you can use the old version that is 100% functional with PHP 5.6 and higher.

Laravel blade tutorial

You can find some tutorials and example on the folder Examples.

You could also check the Wiki

About this version

By standard, The original Blade library is part of Laravel (Illuminate components) and to use this template library, you require install Laravel and Illuminate-view components. The syntax of Blade is pretty nice and bright. It's based in C# Razor (another template library for C#). It's starting to be considered a de-facto standard template system for many PHP (Smarty has been riding off the sunset since years ago) so, if we can use it without Laravel then it's a big plus for many projects. In fact, in theory, it is even possible to use with Laravel. Exists different versions of Blade Template that runs without Laravel, but most requires 50 or more files, and those templates add a new level of complexity, so they are not removing Laravel but hiding:

  • More files to manage.
  • Changes to the current project (if you want to integrate the template into an existent one)
  • Incompatibilities amongst other projects.
  • Slowness (if your server is not using op-cache)
  • Most of the code in the original Blade is used for future use, including the chance to use a different template engine.
  • Some Laravel legacy code.

This project uses a single file called BladeOne.php and a single class (called BladeOne). If you want to use it then include it, creates the folders and that's it!. Nothing more (not even namespaces)*[]: It is also possible to use Blade even with Laravel or any other framework. After all, BladeOne is native, so it's possible to integrate into almost any project.

Why to use it instead of native PHP?

Separation of concerns

Let’s say that we have the next code

//some PHP code
// some HTML code
// more PHP code
// more HTML code.

It leads to a mess of a code. For example, let’s say that we oversee changing the visual layout of the page. In this case, we should change all the code, and we could even break part of the programming.
Instead, using a template system works in the next way:

// some php code
ShowTemplate();

We are separating the visual layer from the code layer. As a plus, we could assign a non-php-programmer in charge to edit the template, and he/she doesn’t need to touch or know our php code.

Security

Let’s say that we have the next exercise (it’s a dummy example)

$name=@$_GET['name'];
echo "my name is ".$name;

It could be separates as two files:

$name=@$_GET['name'];
include "template.php";
// template.php
echo "my name is ".$name;

Even for this simple example, there is a risk of hacking. How? A user could send malicious code by using the GET variable, such as html or even javascript. The second file should be written as follows:

 // template.php
echo "my name is ".html_entities($name);

html_entities should be used in every single part of the visual layer (html) where the user could inject malicious code, and it’s a real tedious work. BladeOne does it automatically.

// template.blade.php
My name is {{$name}}

Easy to use

BladeOne is focused on an easy syntax that it's fast to learn and to write, while it could keep the power of PHP.

Let's consider the next template:

<select>
    <? foreach($countries as $c) { ?>
        <option value=<? echo html_entities($c->value); ?> > <? echo html_entities($c->text); ?></option>
    <? } ?>
</select>

With BladeOne, we could do the same with

<select>
    @foreach($countries as $c)
        <option value={{$c->value}} >{{echo html_entities($c->text)}}</option>
    @nextforeach
</select>

And if we use thehtml extension we could even reduce to

@select('id1')
    @items($countries,'value','text','','')
@endselect()

Performance

This library works in two stages.

The first is when the template calls the first time. In this case, the template compiles and store in a folder.
The second time the template calls then, it uses the compiled file. The compiled file consist mainly in native PHP, so the performance is equals than native code. since the compiled version IS PHP.

Scalable

You could add and use your own function by adding a new method (or extending) to the BladeOne class. NOTE: The function should start with the name "compile"

protected function compileMyFunction($expression)
{
    return $this->phpTag . "echo 'YAY MY FUNCTION IS WORKING'; ?>";
}

Where the function could be used in a template as follows

@myFunction('param','param2'...)

Alternatively, BladeOne allows running arbitrary code from any class or method if its defined.

{{SomeClass::SomeMethod('param','param2'...)}}

Install (pick one of the next one)

  1. Download the file manually then unzip (using WinRAR,7zip or any other program) https://github.com/EFTEC/BladeOne/archive/master.zip
  2. git clone https://github.com/EFTEC/BladeOne (it doesn't include the examples)
  3. Composer. See usage
  4. wget https://github.com/EFTEC/BladeOne/archive/master.zip unzip master.zip

Usage

If you use composer, then you could add the library using the next command (command line)

composer require eftec/bladeone

If you don't use it, then you could download the library and include it manually.

Explicit definition

use eftec\bladeone\BladeOne;

$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';
$blade = new BladeOne($views,$cache,BladeOne::MODE_DEBUG); // MODE_DEBUG allows to pinpoint troubles.
echo $blade->run("hello",array("variable1"=>"value1")); // it calls /views/hello.blade.php

Where $views is the folder where the views (templates not compiled) will be stored. $cache is the folder where the compiled files will be stored.

In this example, the BladeOne opens the template hello. So in the views-folder it should exist a file called hello.blade.php

views/hello.blade.php:

<h1>Title</h1>
{{$variable1}}

Implicit definition

In this mode, it uses the folders __DIR__/views and __DIR__/compiles, also it uses the mode as MODE_AUTO.

use eftec\bladeone\BladeOne;

$blade = new BladeOne(); // MODE_DEBUG allows to pinpoint troubles.
echo $blade->run("hello",array("variable1"=>"value1")); // it calls /views/hello.blade.php

Injection

You can inject the Bladeone using an existing instance of it. If there is no instance, then it will create a new one using the default folders.

$blade=BladeOne::$instance;
echo $blade->run("hello",array("variable1"=>"value1")); // it calls /views/hello.blade.php

Fluent

use eftec\bladeone\BladeOne;

$blade = new BladeOne(); // MODE_DEBUG allows to pinpoint troubles.
echo $blade->setView('hello')    // it sets the view to render
           ->share(array("variable1"=>"value1")) // it sets the variables to sends to the view            
           ->run(); // it calls /views/hello.blade.php

Filter (Pipes)

It is possible to modify the result by adding filters to the result.

Let's say we have the next value $name='Jack Sparrow'

$blade=new BladeOne();
$blade->pipeEnable=true; // pipes are disable by default so it must be enable.
echo $blade->run('template',['name'=>'Jack Sparrow']);

Our view could look like:

 {{$name}}  or {!! $name !!} // Jack Sparrow

What if we want to show the name in uppercase?.

We could do in our code $name=strtoupper('Jack Sparrow'). With Pipes, we could do the same as follows:

 {{$name | strtoupper}} // JACK SPARROW 

We could also add arguments and chain methods.

 {{$name | strtoupper | substr:0,5}} // JACK

You can find more information on https://github.com/EFTEC/BladeOne/wiki/Template-Pipes-(Filter)

Security (optional)

require "vendor/autoload.php";

Use eftec\bladeone;

$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';
$blade=new bladeone\BladeOne($views,$cache,BladeOne::MODE_AUTO);

$blade->setAuth('johndoe','admin'); // where johndoe is an user and admin is the role. The role is optional

echo $blade->run("hello",array("variable1"=>"value1"));

If you log in using blade then you could use the tags @auth/@endauth/@guest/@endguest

@auth
    // The user is authenticated...
@endauth

@guest
    // The user is not authenticated...
@endguest

or

@auth('admin')
    // The user is authenticated...
@endauth

@guest('admin')
    // The user is not authenticated...
@endguest

Custom controls.

There are multiples ways to create a new control (tag)

Extensions Libraries (optional)

BladeOneCache Documentation

https://github.com/eftec/BladeOneHtml

Calling a static methods inside the template.

Since 3.34, BladeOne allows to call a static method inside a class.

Let's say we have a class with namespace \namespace1\namespace2

namespace namespace1\namespace2 {
    class SomeClass {
        public static function Method($arg='') {
            return "hi world";
        }
    }
}

Method 1 PHP Style

We could add a "use" in the template. Example:

Add the next line to the template

@use(\namespace1\namespace2)

and the next lines to the template (different methods)

{{SomeClass::Method()}}
{!! SomeClass::Method() !!}
@SomeClass::Method()

All those methods are executed at runtime

Method 2 Alias

Or we could define alias for each class.

php code:

    $blade = new BladeOne();
    // with the method addAliasClasses
    $blade->addAliasClasses('SomeClass', '\namespace1\namespace2\SomeClass');
    // with the setter setAliasClasses
    $blade->setAliasClasses(['SomeClass'=>'\namespace1\namespace2\SomeClass']);
    // or directly in the field
    $blade->aliasClasses=['SomeClass'=>'\namespace1\namespace2\SomeClass'];

Template:

{{SomeClass::Method()}}
{!! SomeClass::Method() !!}
@SomeClass::Method()

We won't need alias or use for global classes.

Named argument (since 3.38)

BladeOne allows named arguments. This feature must be implemented per function.

Let's say the next problem:

It is the old library BladeOneHtml:

@select('id1')
    @item('0','--Select a country--',"",class='form-control'")
    @items($countries,'id','name',"",$countrySelected)
@endselect

And it is the new library:

@select(id="aaa" value=$selection values=$countries alias=$country)
    @item(value='aaa' text='-- select a country--')
    @items( id="chkx" value=$country->id text=$country->name)
@endselect

The old method select only allows a limited number of arguments. And the order of the arguments is important.

The new method select allows adding different types of arguments

Command Line (CLI)

docs/cli.png

BladeOne (since the version v4.2) allows to run some operations via command line (CLI)

How to run it?

  • Go to your home path and call the PHP script as follows:
php vendor/bin/bladeonecli    # windows/linux/macos
# or you could execute the script as:
./vendor/bin/bladeonecli.bat  # windows
./vendor/bin/bladeonecli      # linux/macos

Or change you folder according to your installation.

And you can set the syntax as follows:

  • -templatepath (optional) the template-path (view paths).
    • Example: '/folder/views' or 'views' (relative)
  • -compilepath (optional) the compile-path.
    • Example: '/folder/compiles or 'compiles' (relative)
  • -clearcompile It deletes the content of the compile-path
  • -createfolder It creates the "compile" and "template" folders
  • -check It checks the library

Clear the compile-folder

php vendor/lib/eftec/bladeone/lib/BladeOne.php -clearcompile

Check the folders, if the folder exists, if it has the right permissions, etc.

php vendor/lib/eftec/bladeone/lib/BladeOne.php -check

Example to clear the compile-folder using a custom compile path

php vendor/lib/eftec/bladeone/lib/BladeOne.php -clearcompile -compilepath mycompile # relative path to the current location
php vendor/lib/eftec/bladeone/lib/BladeOne.php -clearcompile -compilepath /var/mycompile # absolute path (Linux/MacOS)
php vendor/lib/eftec/bladeone/lib/BladeOne.php -clearcompile -compilepath c:\var\mycompile # absolute path (Windows)

BladeOneHtml

It is a new extension to BladeOne. It allows creating HTML components easily and with near-to-native performance.

It uses a new feature of BladeOne: named arguments

Example to create a select:

@select(id="aaa" value=$selection values=$countries alias=$country)
    @item(value='aaa' text='-- select a country--')
    @items( id="chkx" value=$country->id text=$country->name)
@endselect

https://github.com/eftec/BladeOneHtml

You could download it or add it via Composer

composer require eftec/bladeonehtml

Collaboration

You are welcome to use it, share it, ask for changes and whatever you want to. Just keeps the copyright notice in the file.

Future

  • Blade locator/container

License

MIT License. BladeOne (c) 2016-2024 Jorge Patricio Castro Castillo Blade (c) 2012 Laravel Team (This code is based and inspired in the work of the team of Laravel, however BladeOne is mostly an original work)

bladeone's People

Contributors

abdullahezzat1 avatar avonnadozie avatar badakaa avatar bassauer-storms-media avatar daveismynamecom avatar deployhuman avatar fbett avatar jakewhiteley avatar johntaa avatar jorgecc avatar jorgecc-business-account avatar luc-cpl avatar m-mohr avatar marky291 avatar pafernandez-oesia avatar qurben avatar rogervila avatar themagnifico avatar vinkla avatar vishtany avatar xy2z 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

bladeone's Issues

Render view for sitemap

Hello, i have a problem with header content-type.

function sitemap()
{
	header("Content-Type", "text/xml");
            header("HTTP/1.1 200 OK");		
	$data['sitemap']  	= my_sitemap();
	echo $this->blade->run("sitemap", $data);
}

I check the sitemap validity, but it always return text/html.

Sorry for the delay.

I was in Cuba working and the Internet is Cuba is practically nil. Now i have a lot of backlog accumulated. I will check those issues/fixes the next weekend.

See ya

Unable to load Blade v 3.5 and next

Hi,
I've updated from version 3.4 to version 3.7 without change nothing and the plugin won't load anymore. I'm using BladeWithLang. I've also try to downgrade to version 3.5 and the problem still persist. Version 3.4 is okay.

I'm delegating to Composer autoload the loading. So my situation is the following:

config.php file:

require_once ('../vendor/autoload.php');

MyBladeLang.class.php file:

use eftec\bladeone;
use eftec\bladeone\BladeOneLang;

class MyBladeLang extends bladeone\BladeOne {
use BladeOneLang;
}

index.php file:

$blade = new \MyBladeLang($source, $cache, MyBladeLang::MODE_SLOW);

Since 3.4 this was working correctly. Can you explain me what am I doing wrong that stopped to load the class?

Thanks in advance,
Best Regards,

Nested views

Hi, is it possible to use sub_folder/nested_sub_folder/view syntax with BladeOne?

Example:
$blade->run('employment.employee_wizard.index', [ 'titles' => $titles, 'gender' => $gender, // ... ]);

where employment.employee_wizard.index maps to the following:
VIEWS_DIR/Employment/employee_wizard/index.blade.php

asset() not working

It seems asset() function is not in BladeOne yet. Is there any way to inlcude .css and .js files from under /public with BladeOne?

IF @_e with Lang

Hi,
first of all I want to thank you for the project. I really think is a great plugin.
I have a little problem that i can't understand. I'm using bladeone with lang and I can't find a way to do something like this:

{!! ($var == 1) ? @_e('Link Name') : '' !!}

basically @_e('Link Name') always return me an error:
Parse error: syntax error, unexpected '<' in ...

I've also try '@_e('Link Name')' the error is:
Parse error: syntax error, unexpected 'Link' (T_STRING) in ...

Or: '@_e(Link Name)' in this case does not return an error but it prints:
_e(Link Name); ?>

Changeing to this:
{{ ($key == 1) ? '@_e(Link Name)' : '' }}
prints: < ? php echo $this->_e(Link Name); ?>

How can I have "Link Name" printed correctly with Lang ?

thanks in advence,
Best, Ar3s.

Operation not defined:@return

First! Thank you so much for making this functional :)

Sorry to report this, but it looks like "function compileStatements" is picking up @return tags which are created in PHP Comments.

Here's some code from the blade file. I am going to try to prevent this error from continuing, but if you have a way to fix / workaround correctly, please let me know.

Thank you!

Operation not defined:@return

    <script>
        /**
         * Advanced calling object. You can specify custom functions to run at various
         * points in the form submission process.
         */
        var test = {
            /**
             * An example function that is run right before form is submitted via AJAX.
             * @return  void
             */
            beforeSubmit: function ()
            {
                $.vine.log('Form is about to be submitted.');
            },

@auth @endauth

Hi,
I'm looking testsecurity.php but I can't understand much.
How can I let blade know i'm authenticated or not? How does it work with bladelang?

thanks,
A.

@parent should be put back in

@parent Show the original code of the section | REMOVED(*)

Unless there's a better way to handle this, here's an example of @parent and why it's needed:

  • A template contains a JS blade file used for general functions
@section('js_bottom')
<script>
alert('Template JS');
</script>
@endsection
  • A resource view for handling a form post (creating a new user for example):
@section('js_bottom')
<script>
alert('form post js code');
</script>
@endsection('js_bottom')

When you overwrite the section, you lose one of the sections. From what I can tell, the first one sticks, the rest do not.

If you were to add @parent back, the second one could "STACK" to the first, like so, giving you both alerts:

@section('js_bottom')
@parent
<script>
alert('form post js code');
</script>
@endsection('js_bottom')

Change Cache logic

Hi,

The class is great, but I can't see why the BladeOneCache.php file exists in the lib folder when the main class does not use it at all? Also no way to change the caching engine to memory or something else. The file caching logic is hard coded into BladeOne. Am I missing something or is it for some specific reason that the caching must be done in files?

Broken switch for '0' value

Try:

<?php $i = 0; ?>

<h1>test switch where $i={!! $i !!}</h1>
@switch($i)
    @case(0)
    Zero case...
    @break

    @case(1)
    First case...
    @break

    @case(2)
    Second case...
    @break

    @default
    Default case...
@endswitch

It will end up in empty output because 0 == 'RANDOM##VALUE!!!AAAA!!!###AAAA##AA' is true in php.

Also your tests are broken in linux filesystems, in particular

echo $blade->run("test.switch"
        , ["name" => "hello"
            , 'records' => $records
            , 'i' => 44
        ]);

will not find a template, because directory named Test, not test.

Changing the file extension for template files

It would be nice to be able to change the file extension for the template system from .blade.php to .html or somethin different. It is useful for me as I am having an existing system with hundred of existing templates.

Additionally, I think Laravel/Blade supports this, too?!

This is simple as introducing one attribute and a getter and setter for it and then use it in getTemplateFile().

setMode( $mode ) for BladeOne

I understand that global variables are useful when you distinct dev and prod configurations (for example, you're passing constants from .env files), but constants are defined once and kept the same for whole run time. For example, if you want to compile some of templates in one mode, and some in another, you will not able to.

If we had some sort of setMode( $mode ) that will prevail over constant if used, it would be more flexible.

Blade is missing the appendSection method

When you use @section and end it up with @Append you get:

Uncaught Error: Call to undefined method Blade::appendSection()

because there is a "compileAppend" (which matches the @Append) method, but there is no "appendSection" method (which is called from within the compileAppend method)

@inject implementation idea

The current implementation of @inject is not really usable for me right now. The fact that

@inject('myvar', 'NameSpace\MyClass');

Results in

<?php $myvar = new NameSpace\MyClass\myvar(); ?>

would require a custom autoloader which takes this into account and still returns te proper class and I'd rather not have custom resolving logic which might be unpredictable inside my autoloader. Or I would need to name my variables to have the same name as the class, which could result in other problems and is not behaviour I would expect when I see an @inject statement.

I would like to be able to configure what happens when I try to inject a specific class. Something like the following

Config

$blade = new BladeOne($views, $cache, BladeOne::MODE_AUTO);

// The default resolver would be
// function ($className) {
//     return new $className();
// }

$blade->injectResolver(function ($className) {
    // Custom logic for resolving
    return IocContainer::get($className);
});

Blade

@inject('myvar', 'NameSpace\Singleton')

Compiled

<?php $myvar = $this->injectClass('NameSpace\Singleton'); ?>

This would bring it closer to the functionality Laravel provides with @inject, which tries to pull an instance from the app() container.

To keep compatible with the current behaviour the injectClass function could also pass the variable name.

Global variable available everywhere

Hello, I'm trying have a variable available everywhere, in Laravel you'd go about this by using
View::share( 'success', $success );
View::share( 'errors', $errors );

Is there a way to implement this in blade, as i am trying to set my flash messages in the middleware/default controller (it is an old framework) and unset them from the session. I need this to be done once every time the page loads, hence why it is not ok to pass them with
$blade->run($path, $variables); everytime in every controller.

Feature Request: @pushonce directive

Good day Team,

It's really a nice work been done here. This extension has really been helpful in my Codeigniter projects.

I just want to keep a tab on this Feature Request, and this link to an SO post

I'm willing to develop this feature, when I'm free, but I would really appreciate any brief explanation on how to go about it.

Thank you.

run() not passing variable when appear after share()

HI,

My code:

$blade->share('lang', $_lang);  //(I want set variable lang global)

echo $blade->run('layout.banner',  array('var1' => 'content1') );

File: /views/layout/banner.blade.php (Can't get the variable 'var1')

But remove line share() is working!

I do not know why?

CSS Media Queries conflict

I'm using responsive email's the CSS is direct in <head> the problem I have is that:
@media [whatever] { /* CSS... */ }
So every time I try to send an html email it returns compile error because the @media is not defined... s, in order to "fix it" I had to remove my CSS media queries... but my emails doesn't look "responsive"...

Make compiled files deterministic

Thanks for this project, I like how lightweight and straightforward it is.

I am currently using BladeOne to compile templates, which are then sent to a production server, which runs in BladeOne::MODE_FAST. This setup uses git to make sure that only changed files get updated.

The current implementation of BladeOne uses uniqid in the extends implementation. This causes each run of compile/run to result in a different file. Which in my case causes the file to be unnecessarily updated on my production server.

Would it be possible for compileExtends to behave in such a way that it always returns the same output for the same input?

@parent - New issue

After using the @parent update you previously pushed, I am now seeing this echo at the end of my DOM document:

@parentXYZABC

Caching doesn't work when directory doesn't exist

Caching doesn't work when the caching directory doesn't exist, the templating engine can't save the file as file_put_contents fails.

This could be fixed by adding something like:

                $dir = dirname($compiled);
                if (!file_exists($dir)) {
                    $ok = @mkdir($dir, 0777, true);
                    if (!$ok) {
                        $this->showError("Compiling","Unable to create the compile folder [{$dir}]. Check the permissions of it's parent folder.", true);
                    }
                }

before:

                $ok = @file_put_contents($compiled, $contents);

in method compile().

For me this is neccesary as I have a software where you can install different themes and the caching directory is therefore flexible (cache/templates/).

[enhancement] pass data / vars to @yield for sections

I need some tiny component-like views which only contain a few lines of code but are fed with dynamic data from a database - in concrete I need two nested divs with a button that has a dynamic data-attribute. I don't want to create a file for this few lines of code because things will get messy quite quick as the amount of tiny code snippets grow. I know that I could use @include or @component in order to load a view from a file but that's just not what I want. Would it be possible to enable the @yield method to pass data to a section in order to do something like this:

@section('generic_popup_button_markup')
<div class="generic_action_buttons">
    <button class="btn btn-mutateable generic-show-location-on-map-btn" data-marker="{{$popup_id}}">Show location on map</button>
    <button class="btn btn-mutateable">Get in touch for this Object</button>
</div>
@endsection
<!-- some more code and stuff -->
@yield('test', ['popup_id' => $some_db_md5_record])

these buttons/markup is used in several different places and I don't like the thought to do changes to their markup in all sports as soon as it changes

Broken prepare

Hi!
In "3.14" path you broke simple case of preparing templates.
I'm talking about these changes: http://i.imgur.com/wm6WnFP.png

Let's say we have simple class:

class ViewParser extends \portalbladeone\Base
{
    public function __construct($templatesPath, $templatesCompiledPath)
    {
        $this->file = str_replace('.blade.php', '', $file);
        parent::__construct($templatesPath, $templatesCompiledPath);
    }
}

And if you try to do (new ViewParser('/path/to/templates/','/path/to/compiled/templates'))->compile('my_awesome_template', true);, you will get error:
portalbladeone\Exception\BladeError: Read file : Template not found :
Since you deleted $this->fileName = $fileName; part, $compiled = $this->getCompiledFile(); and $template = $this->getTemplateFile(); will get trash.

Also doesn't it do more sense to switch condition from if ($this->isExpired() || $forced) to if ($forced || $this->isExpired())

I can make test and pull request to fix this.

How to Define a Function output to a variable in template?

Hi!

I am using Your template engine with one of my new projects,

I am facing a problem, I can't add function output in every single in "bladeone" run() function.

eg. I have a footer its get the data from the database, and I have created a function to collect data from database and output an array, and I merge the footer in the template array.

But, is there a way I use @set($array=functionname('value')) or an alternative method to define an array through function output in a template and include that template in main site footer?

Thanks,

Output buffer not cleaned on ParseError

Example code:

$bladeSource = <<<'BLADE'
@if($a == 4)
BLADE;
$this->blade->runString($bladeSource, ['a' => 4]);

This thows a ParseError, but the output buffer is not properly cleaned.

BladeOneLogic: Syntax Error using switches

The following code:

@switch($countrySelected)
    @case(1)
        first country selected<br>
    @case(2)
        second country selected<br>
    @defaultcase()
        other country selected<br>
@endswitch()

with

use eftec\bladeone\BladeOne;
use eftec\bladeone\BladeOneHtml;
use eftec\bladeone\BladeOneLogic;;

class Blade extends BladeOne{
    use BladeOneLogic;
}
$blade = new Blade("/var/www/views","/var/www/tmp");
$blade->run("view")

retults in the following error:
Parse error: syntax error, unexpected ' ', expecting case (T_CASE) or default (T_DEFAULT) or '}' in /var/www/tmp/test _a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 on line 2

Add BladeOne to my Wordpress theme

Is it possible to add Bladeone to the wordpress theme I'm developing?
I have installed it using composer and now I have vendor folder in my theme. I have added

require get_stylesheet_directory().'/vendor/autoload';

And I'm trying to add in a shortcode

Use eftec\bladeone;
$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';
$blade=new bladeone\BladeOne($views,$cache,BladeOne::MODE_AUTO);
echo $blade->run("hello",array("variable1"=>"value1"));

I'm getting an error in the Use line
Parse error: syntax error, unexpected 'Use' (T_USE)

compiling empty template causing error

$ok = @file_put_contents($compiled, $optimizedContent); if (!$ok) { $this->showError("Compiling", "Unable to save the file [{$compiled}]. Check the compile folder is defined and has the right permission"); return false; }

file_put_contents returns the number of bytes that were written to the file, or FALSE on failure.

So, here should use $ok===false. In BladeOne.php Line 404.

Aliasing for included templates missing?

I noticed that the last release note said this version is aligned with ver. 5.8, however I cannot find the method for aliasing included views. It was in ver. 5.7 as well, so it may be located under a different method name that I am unable to find.

To get a clearer understanding, this is what I am referencing:

Aliasing Includes

If your Blade includes are stored in a sub-directory, you may wish to alias them for easier access. For example, imagine a Blade include that is stored at resources/views/includes/input.blade.php with the following content:

<input type="{{ $type ?? 'text' }}">

You may use the include method to alias the include from includes.input to input. Typically, this should be done in the boot method of your AppServiceProvider:

use Illuminate\Support\Facades\Blade;

Blade::include('includes.input', 'input');

Once the include has been aliased, you may render it using the alias name as the Blade directive:

@input(['type' => 'email'])

source : https://laravel.com/docs/5.8/blade#including-sub-views

Class eftec\bladeone\BladeOne does not exist

The usage as mentioned under "using composer's autoload.php" is not working.
I am always getting error

Class eftec\bladeone\BladeOne does not exist

I've installed the package via composer. However, it works when I directly include the BladeOne.php file.

How get baseUrl with bladeone?

Hi,
You class BladeOne is amazing, but I have a question, how get baseurl through of a helper?
Twig for slim have the method called baseUrl(), how implement same helper?
example: link
Best regards

Possible wrong class name in doc example

In Usage section under composer example it says to use bladeone\BladeOne class name. In fact composer will not find that class, you have to use eftec\BladeOne\BladeOne instead.

Foreach loop with variable containing "as"

Hi. First of all - great job on single Blade class.

Today had an issue with foreach loop when tried to loop through variable named $cancelReasons.
Checked out compiled file and noticed that something strange was with foreach.
As my variable contained as string then compileForeach() function using preg_match('/\( *(.*) *as *([^\)]*)/', $expression, $matches); split incorrectly @foreach ($cancelReasons as $code => $reason) part.

Don't know if this is correct way to fix it but changing preg_match part to preg_match('/\( *(.*) * as *([^\)]*)/', $expression, $matches); (added space between * as) helped solve my issue.

Maybe there is better way solving this or at least this could help someone.

3.7 @extends is broken.

For an @extends('some.blade.file') BladeOne compiles to

<?php $_shouldextend[{$this->uidCounter}]=1; ?>
...
<?php if (@$_shouldextend[{$this->uidCounter}]) { echo $this->runChild('some.blade.file'); } ?>

Which is not valid php.

CSRF token

The CSRF token field will not refreshed with a new value in the compiled view. Even when mode is set to MODE_SLOW

Suggestion about cache filenames

Why do we need cache filename in format $fileName . ' _' . sha1($fileName) ?

  1. Space in filename may cause problems when you will try to use it in CLI.
  2. sha1($fileName) seems redundant because semantically it's the same with $fileName (same filename will always result in same hash).

I rewrote it to just $fileName . '.php' (because it's basically a regular php files) in my project and it seemed more straightforward.

Remove Laravel dependencies

There are some Laravel dependencies, like calls to app() or Illuminate. As BladeOne usually only makes sense outside of Laravel environments, it doesn't make sense to keep them in the code. Therefore they should be removed.

Enable Travis on repo

Travis should be enabled on the repo now that a config is in place. This allows for automatic test running.

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.