GithubHelp home page GithubHelp logo

webwizo / laravel-shortcodes Goto Github PK

View Code? Open in Web Editor NEW
211.0 9.0 49.0 64 KB

Wordpress like shortcodes for Laravel 4.2, 5.x, 6.x, 7.x, 8.x, 9.x and 10.x

License: MIT License

PHP 100.00%
shortcode laravel wordpress

laravel-shortcodes's Introduction

Laravel-Shortcodes

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads StyleCI

WordPress like shortcodes for Laravel 5.x

[b class="bold"]Bold text[/b]

[tabs]
  [tab]Tab 1[/tab]
  [tab]Tab 2[/tab]
[/tabs]

[user id="1" display="name"]

If you are looking for Laravel 4.2, see: https://github.com/patrickbrouwers/Laravel-Shortcodes

Install

Via Composer

$ composer require "webwizo/laravel-shortcodes:1.0.*"

After updating composer, add the ServiceProvider to the providers array in config/app.php

Usage

Webwizo\Shortcodes\ShortcodesServiceProvider::class,

You can use the facade for shorter code. Add this to your aliases:

'Shortcode' => Webwizo\Shortcodes\Facades\Shortcode::class,

The class is bound to the ioC as shortcode

$shortcode = app('shortcode');

Usage

withShortcodes()

To enable the view compiling features:

return view('view')->withShortcodes();

This will enable shortcode rendering for that view only.

Enable through class

Shortcode::enable();

Disable through class

Shortcode::disable();

Disabling some views from shortcode compiling

With the config set to true, you can disable the compiling per view.

return view('view')->withoutShortcodes();

Default compiling

To use default compiling:

Shortcode::compile($contents);

Strip shortcodes from rendered view.

return view('view')->withStripShortcodes();

Strip shortcode through class

Shortcode::strip($contents);

Registering new shortcodes

Create a new ServiceProvider where you can register all the shortcodes.

php artisan make:provider ShortcodesServiceProvider

After defining shortcodes, add the ServiceProvider to the providers array in config/app.php

Usage

App\Providers\ShortcodesServiceProvider::class,

Callback

Shortcodes can be registered within ShortcodesServiceProvider with a callback:

php artisan make:provider ShortcodesServiceProvider

ShortcodesServiceProvider.php Class File

<?php namespace App\Providers;

use App\Shortcodes\BoldShortcode;
use Illuminate\Support\ServiceProvider;
use Shortcode;

class ShortcodesServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        Shortcode::register('b', BoldShortcode::class);
        Shortcode::register('i', 'App\Shortcodes\ItalicShortcode@custom');
    }
}

Default class for BoldShortcode

You can store each shortcode within their class app/Shortcodes/BoldShortcode.php

namespace App\Shortcodes;

class BoldShortcode {

  public function register($shortcode, $content, $compiler, $name, $viewData)
  {
    return sprintf('<strong class="%s">%s</strong>', $shortcode->class, $content);
  }
  
}

Class with custom method

You can store each shortcode within their class app/Shortcodes/ItalicShortcode.php

namespace App\Shortcodes;

class ItalicShortcode {

  public function custom($shortcode, $content, $compiler, $name, $viewData)
  {
    return sprintf('<i class="%s">%s</i>', $shortcode->class, $content);
  }
  
}

Register helpers

If you only want to show the html attribute when the attribute is provided in the shortcode, you can use $shortcode->get($attributeKey, $fallbackValue = null)

class BoldShortcode {

  public function register($shortcode, $content, $compiler, $name, $viewData)
  {
    return '<strong '. $shortcode->get('class', 'default') .'>' . $content . '</strong>';
  }
  
}

Change log

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

Support me

Buy Me A Coffee

License

The MIT License (MIT). Please see License File for more information.

laravel-shortcodes's People

Contributors

abr4xas avatar alexjoffroy avatar assmay avatar browner12 avatar carsongio avatar josh-taylor avatar kajetan-nobel avatar krishan19 avatar kudashevs avatar laravel-shift avatar lead-worker avatar mebdev avatar professorhaseeb avatar victorybiz avatar vortechron avatar webwizo 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

laravel-shortcodes's Issues

Nested same name tag shortcodes

Hi, i have a problem with nested same name tag shortcode.

Example:

{!! shortcodes('[div class="row"][div class="col-md-6"]Column Left[/div][div class="col-md-6"]Column Right[/div][/div]') !!}

Output:

nested-shortcode

Inspect element:

nested-shortcode-element

Register shortcode:

public function render($content)
    {
        $this->attributes = array_merge($this->attributes, $this->atts);
        return '<div ' . \HTML::attributes($this->atts()). '>'. shortcodes($content) . '</div>';
    }

Thank you.

Next release

Hi !

Since this commit d95aaf9, the package has auto-discovery for provider and facade.

Is it possible (or planned) to release it ?

Laravel 11 supports

Hi,
as subject, please update illuminate requires to 11.x so it can be supported by L11 :)

Laravel 10 Support

Hi there,

can you please update the package, so it does support Laravel 10?

Kind regards

Question : UI Implementation ?

Hello,

Is there some UI implementation for this package to work with tinymce, ckeditor or else ?

( Something like shortcake in wordpress : visual representation in edit box and a modal form to add the shortcode. )

Argument Type issue again

using Laarvel 5.8

Type error: Argument 2 passed to Webwizo\Shortcodes\View\View::__construct() must be an instance of Illuminate\View\Engines\EngineInterface, instance of Illuminate\View\Engines\CompilerEngine given, called in D:\xampp\htdocs\shopping_new\vendor\webwizo\laravel-shortcodes\src\View\Factory.php on line 50

support for Laravel 5.1

Hi,

do you plan support Laravel 5.1? Maybe it's good to change in composer.json:

"illuminate/view": "~5.3",
"illuminate/support": "~5.3",
"illuminate/contracts": "~5.3",

to something like this:

"illuminate/view": "~5.1|~5.2|~5.3",
"illuminate/support": "~5.1|~5.2|~5.3",
"illuminate/contracts": "~5.1|~5.2|~5.3",

and then we can have support for all Laravel 5 versions in one branch. I can prepare PR with this changes.

Strange output

Hi, im have issue with shortcodes..

Shortcode:
public function register($shortcode, $content, $compiler, $name, $viewData)
{
return sprintf('

%s
', $shortcode->class, $content);
}

Compile: {{ \Shortcode::compile('[div class="row"][div class="col-12"]Bold text[/div][/div]') }}

Output:

Bold text
[/div]

Whats wrong here?

Thanks,
Ivan

Selective usage of shortcode not working

Hello,

first of all: Thanks for your great work!
I have the following issue (bug?):

I have the following controller:

Route::get('shortcode', function(){
    return view('test.shortcode')->with("code", '[b class="bold"]Bold text[/b]');
});

Case 1 - As expected
When I use the variable $code in the template like:
{{ $code }}
it works as expected - I only get the raw string as a result:
[b class="bold"]Bold text[/b]

Case 2 - As expected
When I use the variable $code with the compile comand in the template like:
{{ \Shortcode::compile($code) }}
it works as well as expected - I get the (escaped) parsing result:
&lt;strong class=&quot;bold&quot;&gt;Bold text&lt;/strong&gt;
Using it with unescaped blade:
{!! \Shortcode::compile($code) !!}
I get
<strong class="bold">Bold text</strong>

Case 3 - Weird
But when I combine both versions, the result is weird.

{{ $code }}<br>
{{ \Shortcode::compile($code) }}

This is the result:

<strong class="&quot;bold&quot;">Bold text</strong><br>
&lt;strong class=&quot;bold&quot;&gt;Bold text&lt;/strong&gt;

WTF? Why gets the first line ({{ $code }}<br>) parsed and why is the result wrong (&quot;bold&quot;)?

Compile shortcode in Resource for using into an api endpoint

hi
i'm doing an api endpoint for serve some post.
The post content contain some shortcode and on balde view all is ok.
But if i use the withshortcode() ona a resource and return it on the api result nothing was return.

`
public function toArray($request)
{
$compiledcontent = view('onlycontent', [

                'content' => $this->content,
                                   
            ])->withShortcodes();
     return [
        'compiledcontent ' => $compiledcontent ,
     ];

}`

api result:

{"data":[{"compiledcontent":{"shortcode":{}}}],"links":{"first":"http:domain.com/api\post?page=1","last":"http:domain.com/api\post?page=3","prev":null,"next":"http:domain.com/api\post?page=2"},"meta":{"current_page":1,"from":1,"last_page":3,"path":"http:domain.com/api\post","per_page":1,"to":1,"total":3}}
any advices?
is possible to use shortcode on resource?
thanks

Shortcode is not working

Hello,
I have followed all steps. and I used Shortcode::compile($page->contents); in view file it's not working and displaying shortcode.

When I using this return view('pages.show')->withShortcodes('page',$page); code in controller it generating errors.

And Can you please suggest when I put this code "$shortcode = app('shortcode');" ?
I created ioc.php and put this code but it's generating errors.

Please suggest me. And thanks for this latest shortcode library...

Shortocodes on email

Hi

First of all great package.

I can use it for views, but if i use it for mailing, it takes an error:

Code

return $this->from('[email protected]', 'Sender Name')
            ->subject($this->newsletter->subject)
            ->view($this->newsletter->template->view)->withShortcodes();

Error
ErrorException
Undefined offset: 0

Anyone knows what can i do?

Thanks

$viewData is not being passed through to the shortcode

Hi, unless I'm doing something wrong, I think the $viewData is not being passed through to the shortcode.

I think the following needs chaning in src/View/View.php

From:

/**
 * Enable the shortcodes
 */
public function withShortcodes()
{
    $this->shortcode->viewData($this->getData());
    return $this;
}

To:

/**
 * Enable the shortcodes
 */
public function withShortcodes()
{
    $this->shortcode->enable();
    $this->shortcode->viewData($this->getData());
    return $this;
}

handle the blade view extension.

is the possible to include the following for blade view of this shortcode?
I try to include it but it won't show up.

Your help is appreciated. Thank You

@section('scripts')

<script></script>

@Stop

Access data from view

Hi, is there a way to access the passed data from the actual view in the Shortcode?

return view('entities.indx', compact( 'entity'))->withShortcodes();

So that I can do something with $entity while handling the short code ?

Thanks
Felix

Not fully working with all Laravel features (like Markdown emails)

Replacing Illuminate\Contracts\View\Engine by Illuminate\View\Engines\CompilerEngine in src/View/View.php in PR #30 does not fully working with some part of Laravel, like Markdown emails.

I'm not sure why this has to be done, because Illuminate\View\Engines\CompilerEngine implements Illuminate\Contracts\View\Engine ?

public function __construct(Factory $factory, CompilerEngine $engine, $view, $path, $data = [], ShortcodeCompiler $shortcode)

Strip html within shortcode

Hello,
I am doing this:

[tabs]
[tab]something[/tab]
[tab]something[/tab]
[tab]something[/tab]
[/tabs]

but this generates this when the input was done through a WYSIWYG:

<p>[tabs]</p>
<p>[tab]something[/tab]</p>
<p>[tab]something[/tab]</p>
<p>[tab]something[/tab]</p>
<p>[/tabs]</p>

And the shortcode will finally generate something like this:

<p><ul id="tabs16084068915098" class="nav nav-tabs "></p>
<p><li class="nav-item ">
                    <a class="nav-link " id="16084068912629" data-toggle="tab" role="tab" href="#tab16084068912629">
                    Tab1
                    </a>
                </li>
                <div id="tab16084068912629" class="tab ">Tab1 content</div></p>
<p></ul></p>

producing extra

elements and making a non HTML valid list

How do we handle this situation?

remove nested shortcodes

hi , i create a simple shortcode , it return blade and content a post (page) i need way to remove nested shortcode , page in page.
or a simple way remove shortcode [page id='2'] if entered in page editor

create dynamic table row inserting through shortcodes

I'm trying to insert a table row/s dynamically through form by shortcodes functionality.
shortcode : [post id="1,2,3"]
I'm trying to insert table 'post' with id=['1', '2', '3'] rows with my form data.
I have created a new shortcode called InsertAddShortcode and and register it in boot method of ShortcodeServiceProvider.
I have made register method inside InsertAddShortcode.php

public function register($shortcode, $content, $compiler, $name, $viewData)
    {
             $query = $shortcode->table::find($shortcode->id);
            return sprintf($shortcode->table=$query, $shortcode->id= $query->id, $shortcode->class, $content);
    }

but it show error: Class name must be a valid object or a string.

I'm stuck in this process.
Any advice, solution would be highly appreciated.
Thanks in advance!!

using with dompdf

Hi,
I am trying to use your package with dompdf, but not sure how.. can you help me with this?

thanks

Argument 2 passed to Webwizo\Shortcodes\View\View::__construct() must be an instance of Illuminate\View\Engines\EngineInterface

With Laravel 5.6 you get the following error
Argument 2 passed to Webwizo\Shortcodes\View\View::__construct() must be an instance of Illuminate\View\Engines\EngineInterface, instance of Illuminate\View\Engines\CompilerEngine given.
Changing row 6 of Webwizo\Shortcodes\View\View.php to
Argument 2 passed to Webwizo\Shortcodes\View\View::__construct() must be an instance of use Illuminate\Contracts\View\Engine as EngineInterface;
will fix the issue

Malformed shortcodes cause strange output

I found that this comment:

THANK YOU VERY MUCH!
[I AM SO SORRY THAT MY ENGLISH IS POOR ....

Caused some very unexpected output.

THANK YOU VERY MUCH! <em class="fab fa-youtube"></em>

Followed by many lines of my blade template where this should have output inexplicably being skipped - it literally picks up again in the middle of a different section.

Functionnality : Strip conserving content

Current behavior :

Shortcode::strip($string) will remove a shortcode like this : [link href="/toto"]Toto[/link] => `` (empty)

Proposal :

It would be great to add a parameter into strip method in order to keep or not the content, so we can strip like this : [link href="/toto"]Toto[/link] => Toto

attribute having space value converts to weird array.

I.e. [pdfmodal path=/files/docs_5eebb3f1b4e595.53497870.pdf modaltitle='Flat Rate Cost']Click Here[/pdfmodal]

see the argument modaltitle it becomes weird object...

Returns

Shortcode {#1455 ▼
  #name: "pdfmodal"
  #attributes: array:4 [▼
    "path" => "/files/docs_5eebb3f1b4e595.53497870.pdf"
    "modaltitle" => "&#39;Flat"
    0 => "Rate"
    1 => "Cost&#39;"
  ]
  +content: "Click Here"
}

How to prevent that? how to allow spaces in attribute values.

I need way to handle duplicate include ja css

I have galley image and i will use laravel shortcodes to append it in content . I have one problem for handle css or js . Because in shortcode i use push blade js or css . If i use multi shortcode it alway push multiply in footer or js .
Do you can help me how i can use multi shortcode and for all just push one time ?

Use tailwind class custom

By now tailwind (TW) is probably quite popular, with jit-mode in TW3 support that can write dynamic classes of the form h-[400px]

The [...] character unfortunately overlaps with the beginning and end of the shortcode.

Is there any way to support inserting classes in this shortcode or do I have to use style="..."

Thanks for your package and any help from you!!!! <3

Stripping shortcodes from string

Hi,

First of all I'd like to say I absolutely love your package. Just what I needed!

I guess this is more of a feature request, but would it be possible to strip short codes from a string? In some cases you don't want to compile the short codes, but you don't want them to show up either. Would be great to implement such a method in the short code compiler.

Thanks in advance!

How can I use nested code?

How can I use nested shortcode?
for example:
[tabs]
[tab]Tab 1[/tab]
[tab]Tab 2[/tab]
[/tabs]

for this example i should define two shortcode?
one: tabs
two: tab
Shortcode::register('tabs', TabsShortcode::class);
Shortcode::register('tab', TabShortcode::class);

and What should be the content of TabsShortcode & TabShortcode?
please help me
thank you

change document to register new shortcode

hi , instead create new serviceProvider register shortcodes in AppServiceProvider.php


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Shortcodes\BoldShortcode;
use Shortcode;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Shortcode::register('b', BoldShortcode::class);
    }
}

How can we add multiple classes in shortcode ?

I've registered this
Shortcode::register('colmd3', 'App\Shortcodes\ColumnShortcode@colmd3'); into my ShortcodesServiceProvider
while applying it's working fine

[colmd3 class="col-sm-4"]
[/colmd3]

but extra class is not applying

[colmd3 class="col-sm-4 text-center"]
[/colmd3]

This is my ColumnShortcode provider

class ColumnShortcode 
{
  public function colmd3($shortcode, $content)
  {
    return sprintf('<div class = "col-md-3 %s">%s</div>', $shortcode->class, $content);
  }
}

Please help, Thank you

Argument Type issue

I get this error when trying to use shortcode on view
using Laarvel 5.6

Type error: Argument 2 passed to Webwizo\Shortcodes\View\View::__construct() must be an instance of Illuminate\View\Engines\EngineInterface, instance of Illuminate\View\Engines\CompilerEngine given, called in D:\xampp\htdocs\shopping_new\vendor\webwizo\laravel-shortcodes\src\View\Factory.php on line 50

How to pass string as parameter?

Hello,

First, thanks for this wonderful package.

Everything seems to be working fine, but when I try to pass a string as a parameter to a shortcode like so:
[content_block name="Panel List Group"]

Each word gets escaped and split into an array in the Shortcode function.

So:

public function register($shortcode, $content, $compiler, $name)
    {
        print_r($shortcode);
    }

outputs:
[
"name" => "&quot;Panel"
    0 => "List"
    1 => "Group&quot;"
  ]

Has anyone else experienced this?

Problem with shortcode at beginning

hi, i have shortcode: [library type="document" id="68"]

When create some page and i put that code inside text paragraf or after, all working fine!

but, if i put that code at beginning of content [library type="document" id="68"] .... some text then page broken with error:
View [shortcodes.] not found. (View: ...\resources\views\frontend\content\default\content.blade.php)

i have library types: document,gallery, video... inside shortcode function if i call $type to see type or data what i sent to view, all is OK, if i call content inside view for type, a get data what i send. but when i remove dd(), a iget error...

I can't find problem why shortcode is broken if i put on beginning of content!

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.