GithubHelp home page GithubHelp logo

getgrav / grav-plugin-shortcode-core Goto Github PK

View Code? Open in Web Editor NEW
46.0 6.0 20.0 1.26 MB

Grav Shortcode Core Plugin

Home Page: https://getgrav.org

License: MIT License

PHP 39.33% CSS 6.22% JavaScript 54.40% Twig 0.05%
grav grav-plugin shortcode shortcodes shortcode-engine

grav-plugin-shortcode-core's Introduction

Grav Shortcode Core Plugin

About

The Shortcode Core plugin allow for the development of simple yet powerful shortcode plugins that utilize the common format utilized by WordPress and BBCode. The core plugin loads the libraries required and fires a new event that other plugins can use. It also provides a mechanism for adding CSS/JS assets that are cached so that shortcodes can work effectively even when the processed page content is cached. This ensures that shortcodes are only processed once and will not impact performance by doing unnecessary work on every page.

This plugin uses the Thunderer Advanced shortcode engine. For more information please check out that repo on GitHub.

Quick Example

This is some [u]bb style underline[/u] and not much else

[center]This is centered[/center]

This is [size=30]bigger text[/size] and this is [color=blue]blue text[/color]

This example functionality is provided with the Shortcode Core plugin to provide some functionality that is not available in traditional markdown but is standard BBCode used in many form platforms. You can see how the syntax is just a simple open and close element using square brackets.

This will render:

The core plugin required for any other shortcode specific plugin. Provides some basic BBCode style syntax such as underline, color, center, and size.

Installation

Typically a plugin should be installed via GPM (Grav Package Manager):

$ bin/gpm install shortcode-core

Alternatively it can be installed via the Admin Plugin

NOTE: If you install a shortcode plugin such as grav-plugin-shortcode-ui it may have this core plugin configured as a dependency and install it automatically.

Configuration Defaults

The Shortcode Core plugin only has a few options to configure. The default values are:

enabled: true
active: true
active_admin: true
admin_pages_only: true
parser: regular
include_default_shortcodes: true
css:
  notice_enabled: true
custom_shortcodes:
fontawesome:
  load: true
  url: '//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css'
  v5: false
  • enabled: true|false toggles if the shortcodes plugin is turned on or off
  • active: true|false toggles if shortcodes will be enabled site-wide or not
  • active_admin: true|false toggles if shortcodes will be processed in the admin plugin
  • admin_pages_only: true|false toggles if admin should only process shortcodes for Grav pages
  • parser: wordpress|regex|regular let's you configure the parser to use
  • include_default_shortcodes: true|false toggle the inclusion of shortcodes provided by this plugin
  • custom_shortcodes: the path to a directory where you can put your custom shortcodes (e.g. /user/custom/shortcodes)
  • fontawesome.load: true|false toggles if the fontawesome icon library should be loaded or not
  • fontawesome.url: the CDN Url to use for fontawesome
  • v5: Version 5 flag as it requires some additional logic

NOTE: In previous versions the wordpress parser was preferred. However with version 2.4.0, the regex parser is now default. If you have saved configuration, you should manually change this to regex or you may receive errors or bad output.

Configuration Modifications

The best approach to make modifications to the core plugin settings is to copy the shortcode-core.yaml file from the plugin into your user/config/plugins/ folder (create it if it doesn't exist). You can modify the settings there.

NOTE: If you have the admin plugin installed, you can make modifications to the settings via the Plugins page and it will create that overridden file automatically.

Per-Page Configuration

Sometimes you may want to only enable shortcodes on a page-by-page basis. To accomplish this set your plugin defaults to:

enabled: true
active: false

This will ensure the plugin is loaded, but not active, then on the page you wish to process shortcodes on simply add this to the page header:

shortcode-core:
    active: true

This will ensure the shortcodes are processed on this page only.

You can also change the parser on a particular page with the following:

shortcode-core:
    parser: regex

Available Shortcodes

The core plugin contains a few simple shortcodes that can be used as basic examples:

Underline

Underline a section of text

This is some [u]bb style underline[/u] and not much else

Font Size

Set the size of some text to a specific pixel size

This is [size=30]bigger text[/size]

Left Align

Left align the text between this shortcode

[left]This text is left aligned[/left]

Center Align

Center a selection of text between this shortcode

[center]This text is centered[/center]

Right Align

Right align the text between this shortcode

[right]This text is right aligned[/right]

Div

Allows you to wrap markdown in an HTML div tag that supports both id and classes attributes

[div class="text-center"]
This text is **centered** aligned
[/div]

or

[div class="table table-striped"]
| header 1 | header 2 |
|----------|----------|
| A 1      | B 1      |
| A 2      | B 2      |
| A 3      | B 3      |
[/div]

Headers

Allows you to add id and class attributes to HTML h1 through h6 tags:

[h1 class="major"]This is my title[/h1]

Span

Allows you to wrap markdown in an HTML span tag that supports both id and class attributes

[span class="text-center"]
This text is **centered** aligned
[/span]

Columns

Take advantage of powerful CSS columns support by using this shortcode

[columns]
### Headline

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
[/columns]

Defaults to 2 columns. You can also explicitly set the number of columns, width, gap, and rule styling for the column divider:

[columns count=3 width=200px gap=30px rule="1px dotted #930"]
### Headline

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
[/columns]

Raw

Do not process the shortcodes between these raw shortcode tags

[raw]This is some [u]bb style underline[/u] and not much else[/raw]

Safe-Email

Encode an email address so that it's not so easily 'scrapable' by nefarious scripts. This one has a couple of options: autolink toggle to turn the email into a link, an icon option that lets you pick a font-awesome icon to prefix the email, and a subject option that let's you specify the subject line for the user's mail agent to prefill. All settings are optional.

Safe-Email Address: [safe-email autolink="true" icon="envelope-o" subject="Feedback"][email protected][/safe-email]

Section

The section shortcode is a powerful way to encompass some text in your markdown page with a [section][/section] tag and then this is cached by Grav so it can be accessed later. For example you could have a page with a variety of sections described in it that let you create many chunks of data. These are then added to Twig as an array of shortcode objects. An example of this would be the following markdown:

[section name="author"]
![](author.jpg?cropResize=100,100&classes=left)
### Johnny Appleseed
Johnny Appleseed was an American pioneer nurseryman who introduced apple trees to large parts of Pennsylvania, Ontario, Ohio, Indiana, and Illinois, as well as the northern counties of present-day West Virginia. He became an American legend while still alive, due to his kind, generous ways, his leadership in conservation, and the symbolic importance he attributed to apples.
[/section]

[section name="quote"]
> Some are born great, some achieve greatness, and some have greatness thrust upon them.
  Read more at http://www.brainyquote.com/quotes/topics/topic_great.html#tdqt3strtEYBCH43.99
> <cite>William Shakespeare</cite>

Regular **Markdown** content that will be output as `page.content`
[/section]

This we be removed from the page content and made available in Twig variables so you could insert these into custom HTML structures, for example:

<div id="author">{{ shortcode.section.author }}</div>

<div id="article">
    <div class="left">
        {{ page.content|raw }}
    </div>
    <div class="right">
        {{ shortcode.section.quote }}
    </div>
</div>

Sections from other pages

You can even retrieve a section from another page utilizing the shortcodes as they are stored in the page's contentMeta with this Twig syntax:

<div id="author">{{ page.find('/my/custom/page').contentMeta.shortcodeMeta.shortcode.section.author }}</div>

There may be a scenario where you define a section in another page, but want to use it in the content of a page. You can now do so with the same [section] shortcode by providing the page where the section is defined, and also the name of the section with no shortcode body. For example

[section page="/my/custom/page" name="author" /]

!! NOTE for this to work, the shortcode needs to be defined a parent page, or page that has been processed before the current page.

Notice

A useful shortcode that performs a similar job to the markdown-notices plugins, allows you to easily create simple notice blocks as seen on http://learn.getgrav.org and http://getgrav.org. To use simply use the following syntax:

[notice]
Your **Markdown** text that will appear in the notice
[/notice]

You can also specifically choose from note, info, warning, tip types which provide unique color options:

[notice=warning]
Danger Will Robinson! Danger, Will Robinson!
[/notice]

Figure

Figure elements are the recommended way to add self-contained units of flow content, i.e. images, charts and other visual elements that can be moved away from the main flow of the document without affecting the document's meaning. Figures may include captions through the caption attribute. Both id and class attributes are also available.

[figure id="fig1" class="image" caption="**Fig. 1** A beautiful figure."]
![Gorgeous image](image.png)
[/figure]

Mark

The HTML <mark></mark> tag is extremely useful to highlight text in your pages, and serves like a highlighter pen. However, as we know that markdown inside of HTML is not processed, using this HTML is often not convenient as it means markdown inside will not be processed.

Another important usecase is trying to highlight code in a markdown text block, again the HTML tag doesn't work because the result is escaped and treated like any other code and simply displayed.

The solution is simple, just use the shortcode version instead:

This is a sample of text [mark]with this bit **highlighted** with _markdown_ syntax[/mark] and the rest just plain.

You can also use the class option to specificy a specific a CSS class to add to the <mark> HTML tag (useful to color the marked output):

This is a sample of text [mark class=blue]with this bit **highlighted** with _markdown_ syntax[/mark] and the rest just plain.

It also works great in code blocks:

<?php
class Pipeline extends PropertyObject
{
    use AssetUtilsTrait;

    [mark]protected const CSS_ASSET = true;[/mark]
    protected const JS_ASSET = false;

    ...
}

You can also pass an option style attribute of block to get a full lines highlighted:

<?php
class Pipeline extends PropertyObject
{
    use AssetUtilsTrait;

    [mark style=block]
    protected const CSS_ASSET = true;
    protected const JS_ASSET = false;
    [/mark]

    ...
}

Language

Hooks into Grav's multi-language capabilities to allow you to show certain blocks of code only for the current active language.

[lang=en]
Or kind rest bred with am shed then.
[/lang]

[lang=fr]
Marche diable ombres net non qui.
[/lang]

[lang=de]
Genie dahin einem ein gib geben allen.
[/lang]

FontAwesome

FontAwesome is a powerful library of font-based icons. This shortcode makes it simple to add fontawesome icons to your page content without using HTML.

[fa=cog /] Simplest Format

[fa=fa-cog /] Format using `fa-` prefix

[fa icon=fa-camera-retro /] Explicit format

[fa icon=fa-grav extras=fab /] Font Awesome 5 format

[fa icon=fa-camera-retro extras=fa-4x /] Explicit format with extras - [See FontAwesome Examples](https://fortawesome.github.io/Font-Awesome/examples/)

[fa icon=fa-circle-o-notch extras=fa-spin,fa-3x,fa-fw,margin-bottom /] The full monty! - [See FontAwesome Examples](https://fortawesome.github.io/Font-Awesome/examples/)

Details/Summary

The <details> element provides a simple show/hide behaviour without JavaScript, and can optionally contain a <summary> element that is always shown. Clicking on the summary text toggles the visibility of the content, and when a summary is not provided, it defaults to "Details". The element can be used to provide extra details, or can be combined into an accordion-like structure.

[details]
Lorem ipsum dolor sit amet...
[/details]

[details="Summary text"]
Lorem ipsum dolor sit amet...
[/details]

[details summary="Summary text" class="accordion"]
Lorem ipsum dolor sit amet...
[/details]

Note: The show/hide behaviour is not supported in IE 11 or Edge 18, and the element will be permanently open. You can check the current status of browser compatibility at Can I Use.

Lorem Ipsum

Useful for faking content, you can use a shortcode to quickly generate some random "lorem ipsum" text:

Paragraphs:

[lorem=5 /]

[lorem p=5 tag=div /]

Sentences:

[lorem s=4 /]

Words:

[lorem w=35 /]

Using Shortcodes in Twig

You can now use shortcodes in Twig templates and process them with the |shortcodes filter. For example:

{% set twig_text = "This is [size=30]bigger text[/size] and this is [color=green]green text[/color]" %}
{{ twig_text|shortcodes }}

Custom Shortcodes

Simple Way

First, configure a directory from which custom shortcodes are loaded. Edit user/config/plugins/shortcode-core.yaml like follows (create it if it does not exist):

custom_shortcodes: '/user/custom/shortcodes'

To add a custom shortcode, create a PHP file that defines a new shortcode class. For example, to create a shortcode for strikethrough text, save the following code as user/custom/shortcodes/StrikeShortcode.php:

<?php
namespace Grav\Plugin\Shortcodes;

use Thunder\Shortcode\Shortcode\ShortcodeInterface;

class StrikeShortcode extends Shortcode
{
    public function init()
    {
        $this->shortcode->getHandlers()->add('strike', function(ShortcodeInterface $sc) {
            return '<del>'.$sc->getContent().'</del>';
        });
    }
}

Note that the class name (StrikeShortcode) must match the file name for the shortcode to work.

[strike]text[/strike] should now produce strikethrough text.

As a Custom Plugin

The more flexible approach is to create a custom plugin.

The Shortcode Core plugin is developed on the back of the Thunderer Advanced Shortcode Engine and as such loads the libraries and classes required to build third party shortcode plugins.

We introduced a new event called onShortcodeHandlers() that allows a 3rd party plugin to create and add their own custom handlers. These are then all processed by the core plugin in one shot.

    public static function getSubscribedEvents()
    {
        return [
            'onShortcodeHandlers' => ['onShortcodeHandlers', 0]
        ];
    }

Then you just need to listen to the event:

    public function onShortcodeHandlers()
    {
        $this->grav['shortcode']->registerAllShortcodes(__DIR__.'/shortcodes');
    }

Lastly create your shortcode in the user/plugins/my-plugin/shortcodes/ folder, in this example we created a simple [red][/red] shortcode as RedShortcode.php:

<?php
namespace Grav\Plugin\Shortcodes;

use Thunder\Shortcode\Shortcode\ShortcodeInterface;

class RedShortcode extends Shortcode
{
    public function init()
    {
        $this->shortcode->getHandlers()->add('red', function(ShortcodeInterface $sc) {
            return '<span style="color:red;">'.$sc->getContent().'</span>';
        });
    }
}

If you have not already done so, I suggest reading the Grav Plugin Tutorial first to gain a full understanding of what you need to develop a Grav plugin.

The best way to see how to create a new shortcode-based plugins is to look at the Shortcode UI plugin that extends the Shortcode Core by adding more shortcodes. It also makes use of Twig to handle processing and has some more advanced shortcode techniques.

Processing Shortcodes Before or After Markdown processing

There are basically two ways of processing a shortcode:

  1. After markdown is processed
  2. Before markdown is processed

These two approaches are important because, for the most part, shortcodes make more sense when they can 'wrap' markdown, so they process after markdown.

For example a [div][/div] shortcode would be useless if it ran before markdown is processed because it would add the relevant HTML <div></div> tags, and then the markdown parser would promptly skip all markdown processing between those divs because it won't process markdown inside HTML. So this shortcode and most others run after markdown processing has already occurred using this approach:

$this->shortcode->getHandlers()->add('div', function(ShortcodeInterface $sc) { ... }

Notice the getHandlers() call is the standard way to add a handler.

However, there are situations when you need to process the shortcode before the markdown processing to ensure markdown is skipped, like in the example of a code block. This is why in the Prism Highlighter plugin, we use this approach to defining the shortcode:

$this->shortcode->getRawHandlers()->add('prism', function(ProcessedShortcode $sc) { ... }

The difference here is it uses getRawHandlers() to ensure the handler is processed to the content in the raw state.

Display All Shortcodes

You can now display all available shortcodes by using the CLI command:

bin/plugin shortcode-core display

grav-plugin-shortcode-core's People

Contributors

a---- avatar finanalyst avatar giansi avatar gsalvatella avatar hc-sven avatar hotdoy avatar k8n avatar kalagon avatar mahagr avatar markus00000 avatar miguelsalespereira avatar n-parsons avatar newkind avatar pamtbaau avatar pgrimaud avatar rhukster avatar w00fz avatar webmasterslava avatar woutgg 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

grav-plugin-shortcode-core's Issues

Rendering Twig Template with Shortcode

Hi, I have a simple question here:
If I have a shortcode I want to render a Twig Template. How would I go about implementing this in Grav?

Example: My shortcode is [news] when this occurs the template partials/news.twig (i.e. {% include 'partials/news.twig' %}) should be inserted into the page. Is this possible or is this too late when the shortcodes are rendered?

Markdown inside shortcodes not processed with twig |markdown filter

I wonder if this is a Grav or a Shortcode issue or expected behavior, or if this issue is related, but I'll describe the scenario:

I need to do some parsing to the page content before rendering in markdown, so:

  • I've disabled markdown in the frontmatter
  • then I do some content splitting and parsing in twig in the template
  • and then finally render the split parts using twig |markdown filter

Problem is that, even with markdown extra, content inside shortcodes (such as [div]…[/div]) then won't get rendered in markdown.

I've tried newlines etc., but at the moment the workaround looks like this:

---
process:
  markdown: false
---

[div]{{"

### Markdown content here

I'm an ugly workaround

"|markdown}}[/div]

…which works, but defeats the purpose of the exercise, which is to create complex long-pagers with a single, minimal markdown document with unobtrusive section dividers, a bit like the example in the docs where you render content separated by ---'s in columns, but I'm adding some parsing to throw some id's/classes in, too.

Size doesn't work ?

Hello there,

I've tried to use the size shortcode like this [size=10]test[/size]

Here is the result:

<span style="font-size: =10px;">test</span>

Am I the only one ?

Latest Update Breaks FontAwesome

Hey, I just updated to the latest version and my FontAwesome icons break. It looks like it not honoring the following Markdown formats:

[fa=cog /] Simplest Format
[fa=fa-cog /] Format using fa- prefix

It is however, honoring this format: [fa icon=fa-cog /].

I haven't tested the "extras" options yet.

Thanks.

Custom shortcodes in theme

Is it possible to add new custom shortcodes in a location outside of the plugins folder? Like a new folder in the user/ folder or as part of a theme?

Error on page using shortcode

Just updated the shortcode-core plugin. After that, I get the following error on the one page where I make use of shortcode:

Argument 1 passed to Grav\Plugin\ShortcodeManager::getId() must implement interface Thunder\Shortcode\Shortcode\ShortcodeInterface, null given, called in /Users/phytzel/Sites/grav/user/plugins/shortcode-ui/shortcodes/AccordionsShortcode.php on line 33

The error page lists the following chunk from
/Users/phytzel/Sites/grav/user/plugins/shortcode-core/classes/ShortcodeManager.php


    /**
     * returns the shortcode of a specific hash
     * 
     * @param  string $hash       unique id of state
     * @return ShortcodeInterface shortcode stored for this hash
     */
    public function getStates($hash)
    {
        if (array_key_exists($hash, $this->states)) {
            return $this->states[$hash];
        }
    }
 
    /**
     * helper method to create a unique shortcode based on the content
     * 
     * @param  ShortcodeInterface $shortcode
     * @return string             
     */
    public function getId(ShortcodeInterface $shortcode)
    {
        return substr(md5($shortcode->getShortcodeText()), -10);
    }
 
    /**
     * Sets the current page context
     *
     * @param Page $page
     */
    public function setPage(Page $page)
    {

and highlights the line with getId().

It appears that the new shortcode-core does not work properly together with shortcode-ui.

Which further output should I provide?

Custom Shortcodes removed with update

I am running a site that uses the shortcodes plugin and I have created a few custom shortcodes in the /user/plugins/shortcode-core/shortcodes/ folder.

But every time I update the plugin they are removed. I have backups which I can replace the missing files with but is there a way to create a folder outside of the plugin directory (either in a user/theme/myCustomTheme/ or directly in the user/ folder) that can be read by the plugin but not updated (thus removing any custom contents)?

Disappearing twig_vars

With both the TwigFeeds-plugin and the Shortcode Core-plugin active, the latter is removing twig_feeds from .twig_vars when in the module-context. That is, {{ dump(twig_feeds) }} will return the active feeds on a modular page's template (eg. modular.html.twig), but not when used on a module's template (eg. text.html.twig).

For example, installing the Core (v1.1.17) + Admin (v1.2.14) package, TwigFeeds v2.0.3, and Shortcode Core v2.5.3, adding {{ dump(grav.twig.twig_vars.twig_feeds) }} to user/themes/antimatter/templates7modular/text.html.twig will return null in the Debugger with Shortcode Core enabled. With it disabled, however, feeds are returned as an array. In the parent-template it returns regardless.

X-ref: TwigFeeds issue 4.

Color Breaks in Grav 1.5.8 / Shortcode Core 3.1.0

WordPress parser (default setting) is broken in the latest Grav + Shortcode Core. Switching to Regex or Regular fixes it. Color renders as a span without the color assignment on WordPress parser.

Shortcode breaks modular Forms

I'm using the Forms v2.13.3 and Shortcode Core v2.7.1 plug-ins in Grav v1.4.3. As soon as I enable the Shortcode Core plug-in, forms inside modular pages no longer get populated (only the container HTML is generated, but no dynamic content, such as input fields and buttons).

I'm using the classical method of rendering forms in modular pages as described in the Grav manual, i.e. my parent page contains the form frontmatter, and the modular page consists of form.md with the following contents:

---
title: 'My Form'
cache_enable: false
---

Add documentation on using debugger with admin plugin

This took forever to figure out, so I'm hoping this issue can be a launching point for writing some documentation on a painful edge case I ran into when trying to build & debug a new shortcode extension. The TLDR is a docs that says something like this "for code running inside shortcode handler functions, to output debug information you should either return the log information as part of the shortcode handler return value, or you should use the grav log. Usage of the grav debugger will work in most situations, but log information will not be displayed inside the admin plugin"

Here's why (The following issue assumes all caching is turned off, so every request should re-trigger processing....)

When using the editor (at /admin/pages/<page route>) you are by default in the "Editor" mode. When you switch into the "Preview" mode, you can see the end result of your custom shortcode handler logic. However, if you have Grav debugger statements inside your shortcode handler function, they will not be displayed in the page's debugger log

The problem is that clicking "Preview" triggers a "processMarkdown" AJAX call to awaken grav and handle processing the markdown and by extension calling shortcode-core which will call your custom shortcode handler logic. Processed content will be returned via the same AJAX call via the magic of the admin plugin, but the debugger log contents are not returned.

On a different note, I went down this rabbit hole of debugging because my shortcodes work fine on /admin/preview/... but do not work on /admin/pages/.... It currently seems some high level information is different between those two, e.g. the $page variable changes.

[columns] not working correctly

When i use the [columns] Shorttag with 4 Images then Then it looks like this:
image

Code:

[columns count=4]
[![](GitHub_Logo.png)](https://github.com/)

[![](BunnyCDN_Logo.png)](https://bunnycdn.com/)

[![](TravisCI_Logo.png)](https://travis-ci.org/)

[![](OVH_Logo.png)](https://ovh.com)
[/columns]

Shortcode breaks LangSwitcher

Hello,

I'm trying to use the Shortcode Core plugin v2.0.2, but when it is enabled it seems like breaks the LangSwitcher v1.1.0 plugin, specifically the variable langswitcher.current becomes empty if it is inside a modular page template. Maybe I am missing something here? Please help me understand. Thanks!

Here is some minimal sample code to reproduce the issue:

config/system.yaml
languages:
  supported:
    - en
    - el
    - fr

cache:
  enabled: false

twig:
  cache: false
config/plugins/langswitcher.yaml
enabled: true
built_in_css: false
config/plugins/shortcode-core.yaml
enabled: true
active: false
active_admin: false
parser: wordpress
load_fontawesome: false
pages/01.home/modular.en.md

---
title: 'Foo'
menu: Home
onpage_menu: true
content:
    items: @self.modular
    order:
        by: default
        dir: asc
        custom:
            - _header

---
pages/01.home/_header/header.md

---
title: Home

---
templates/modular.html.twig
{% extends 'partials/base.html.twig' %}
...
{% block content %}
    {{ page.content }}
    {% for module in page.collection() %}
        {{ module.content }}
    {% endfor %}
{% endblock %}
...
templates/partials/base.html.twig
<!DOCTYPE html>
...
<head>
  ...
</head>
<body>
  {% block nav %}
      {% set lang = langswitcher.current %}
      <!-- this works ok output is <span>---en---</span> -->
      <span>---{{lang}}---</span>
  {% endblock %}
  {% block body %}
    {% block content %}{% endblock %}
  {% endblock %}
  ...
</body>
</html>
templates/modular/header.html.twig
templates/modular/header.html.twig
      {% set lang = langswitcher.current %}
      <!-- this does not work output is <span>------</span> -->
      <span>---{{lang}}---</span>

When shortcode-core is enabled, header.html.twig produces:
<span>------</span>

If it is disabled, the output is:
<span>---en---</span>

Sections are not cached

When cache is enabled, sections are displayed only when the cache is built the first time.

Size SC with named & other units

CSS allows for the font-size attribute to have values such as x-large, and units such as pt or %.

Current implementation of [size=...] sticks px onto the parameter. This reduces flexibility.

Suggest change so that px is concatenated to parameter value only when parameter is a number.

See PR #63

Exception error just after installing plugin

Hi,
I've installed the plugin several times but I always receive an error message that breaks my whole site after installing the plugin. I attach you a screenshot of it:
captura de pantalla 2016-03-22 a les 17 52 56

I hope you can help me with this issue.
Thanks!

Current shortcode processing hook comes too late

Seems like the current hook is too late for several use-cases.

Example 1: Shortcodes and assets on modular pages

As seen in this issue, shortcodes don't correctly add assets when used in modular pages.

Example 2: Markdown processing

As seen in this PR, shortcodes might add unwanted markup.

Mulitple Columns Sections on one page

Maybe easy fix or my misunderstanding but i am unable to use multiple columns short codes on one page.
My page looks like this:

  1. Text
    [columns] Unordered list [/columns]
  2. Text
    [columns] Unordered list [/columns]
    ...etc

columns short code works only for first time then it looks like it is ignored.

no columns in firefox

installed latest shortcode-core 2.5.1. though you added moz-columns --> no columns in firefox.
cleared all caches, tried diffrent processor settings...no columns

Memory Error

After upgrading the lasted version, I am getting a memory error:

E_ERROR - Allowed memory size of 134217728 bytes exhausted (tried to allocate 1052672 bytes)

Using GRAV v1.5.4

Last update destroys GravStrap menus

Was working on new site using Gravstrap. Got notice of update for shortcode core and did so. Now the header / footers menus are gone, totally missing from entire site. Downgraded to version b4 update and all menus restored.

I am also working on a new bootstrap theme for Grav and it was effected same way.

Thanks!

Woody

Shortcode replace p tags by div

After having used [center][/center] around some text in a markdown, I found out that the result was some raw text on the web page, stripped from all the CSS.

The reason is the CSS I built is defined on <p> tags, and that the Shortcode plugin outputs text lines in <div>, with just inline "style" attribute. Here is the sourcecode :

<p><div style="text-align: center;">Envoyez un message à l'aide du formulaire de contact ou contactez-nous par téléphone.</div></p>

But styling <div> to render text properly is more difficult than styling <p> tags, and can lead to conflicts. Not mentioning that they are not made for this semantic purpose. So, my suggestion would be to fix the problem by embedding correctly the content catched by the plugin ! For instance :
<div style="text-align: center;">
<p>Some text<p>
</div>

Or, more efficiently, by acting on the <p> tag itself :
<p style="text-align: center;">Some text</p>

Something funky with Admin plugin and Shortcodes

Moved from here at @rhukster 's request.

I have a couple of shortcode plugins. I've received bug reports for Scheduler and Table Importer. It seems related to the Admin plugin somehow. I've done the following:

  1. I did a clean install of Grav only (no Admin).

  2. I then did bin/gpm install table-importer.

  3. I replaced default.md with the following and dropped in import.csv.

---
title: test
---

[u]Testing[/u]

[ti file=import.csv /]
  1. It works as expected.

  2. I then downloaded and installed Grav+Admin and immediately did bin/gpm install table-importer.

  3. I added some dump() statements to table-importer.php.

  4. I then dropped in the exact same markdown and csv.

  5. It fails.

So it appears the onShortcodeHandlers isn't getting called for some reason, but the [u] code is working. Any ideas?

align-shortcodes breaks css styling

adding center/left/right shortcodes to a text breaks css styling.
text not rendered as paragraph anymore, only as element. paragraph css style gets lost.

Shortcodes break markdown code

Hello,
Since the last version, you can't use shortcodes around markdown :(

For exemple I often use [center] around images like this [center]![My Image](image_src.jpeg)[/center]. With the last release, this code doesn't work anymore, it just shows ![My Image](image_src.jpeg) as plain text but centered though...

Other example
[size=10]_some text_[/size] renders _some text_ with size 10 but not italic... So the shortcode is rendered but not the markdown...

shortcode-core breaks entire grav install??

getgrav/grav-plugin-admin#487

I will copy it here:

It seems like it is gravstrap plugin, but I could be wrong. I don't remember changing anything that caused this break, but is it possible that I deleted a line or something and accidentally broke something. Anyway, the error message is:

Whoops\Exception\ErrorException thrown with message "Argument 1 passed to Grav\Plugin\ShortcodeManager::getId() must implement interface Thunder\Shortcode\Shortcode\ShortcodeInterface, null given, called in
C:\wamp\www\grav\user\plugins\gravstrap\classes\Base\GravstrapShortcode.php on line 204 and defined"

Stacktrace:
#27 Whoops\Exception\ErrorException in C:\wamp\www\grav\user\plugins\shortcode-core\classes\ShortcodeManager.php:264
#26 Whoops\Run:handleError in C:\wamp\www\grav\user\plugins\shortcode-core\classes\ShortcodeManager.php:264
#25 Grav\Plugin\ShortcodeManager:getId in C:\wamp\www\grav\user\plugins\gravstrap\classes\Base\GravstrapShortcode.php:204
#24 Grav\Plugin\Shortcodes\GravstrapShortcode:registerOutput in C:\wamp\www\grav\user\plugins\gravstrap\shortcodes\Basic\GravstrapSectionShortcode.php:67
#23 Grav\Plugin\Shortcodes\GravstrapSectionShortcode:renderOutput in C:\wamp\www\grav\user\plugins\gravstrap\classes\Base\GravstrapShortcode.php:65
#22 Grav\Plugin\Shortcodes\GravstrapShortcode:Grav\Plugin\Shortcodes\{closure} in C:\wamp\www\grav\user\plugins\shortcode-core\vendor\thunderer\shortcode\src\Processor\Processor.php:134
#21 call_user_func_array in C:\wamp\www\grav\user\plugins\shortcode-core\vendor\thunderer\shortcode\src\Processor\Processor.php:134
#20 Thunder\Shortcode\Processor\Processor:processHandler in C:\wamp\www\grav\user\plugins\shortcode-core\vendor\thunderer\shortcode\src\Processor\Processor.php:93
#19 Thunder\Shortcode\Processor\Processor:processIteration in C:\wamp\www\grav\user\plugins\shortcode-core\vendor\thunderer\shortcode\src\Processor\Processor.php:53
#18 Thunder\Shortcode\Processor\Processor:process in C:\wamp\www\grav\user\plugins\shortcode-core\classes\ShortcodeManager.php:228
#17 Grav\Plugin\ShortcodeManager:processContent in C:\wamp\www\grav\user\plugins\shortcode-core\shortcode-core.php:90
#16 Grav\Plugin\ShortcodeCorePlugin:onPageContentProcessed in C:\wamp\www\grav\vendor\symfony\event-dispatcher\EventDispatcher.php:181
#15 call_user_func in C:\wamp\www\grav\vendor\symfony\event-dispatcher\EventDispatcher.php:181
#14 Symfony\Component\EventDispatcher\EventDispatcher:doDispatch in C:\wamp\www\grav\vendor\symfony\event-dispatcher\EventDispatcher.php:46
#13 Symfony\Component\EventDispatcher\EventDispatcher:dispatch in C:\wamp\www\grav\vendor\rockettheme\toolbox\Event\src\EventDispatcher.php:23
#12 RocketTheme\Toolbox\Event\EventDispatcher:dispatch in C:\wamp\www\grav\system\src\Grav\Common\Grav.php:449
#11 Grav\Common\Grav:fireEvent in C:\wamp\www\grav\system\src\Grav\Common\Page\Page.php:561
#10 Grav\Common\Page\Page:content in C:\wamp\www\grav\user\plugins\gravstrap\gravstrap.php:89
#9 Grav\Plugin\GravstrapPlugin:onTwigSiteVariables in C:\wamp\www\grav\vendor\symfony\event-dispatcher\EventDispatcher.php:181
#8 call_user_func in C:\wamp\www\grav\vendor\symfony\event-dispatcher\EventDispatcher.php:181
#7 Symfony\Component\EventDispatcher\EventDispatcher:doDispatch in C:\wamp\www\grav\vendor\symfony\event-dispatcher\EventDispatcher.php:46
#6 Symfony\Component\EventDispatcher\EventDispatcher:dispatch in C:\wamp\www\grav\vendor\rockettheme\toolbox\Event\src\EventDispatcher.php:23
#5 RocketTheme\Toolbox\Event\EventDispatcher:dispatch in C:\wamp\www\grav\system\src\Grav\Common\Grav.php:449
#4 Grav\Common\Grav:fireEvent in C:\wamp\www\grav\system\src\Grav\Common\Twig\Twig.php:310
#3 Grav\Common\Twig\Twig:processSite in C:\wamp\www\grav\system\src\Grav\Common\Grav.php:186
#2 Grav\Common\Grav:Grav\Common\{closure} in C:\wamp\www\grav\vendor\pimple\pimple\src\Pimple\Container.php:113
#1 Pimple\Container:offsetGet in C:\wamp\www\grav\system\src\Grav\Common\Grav.php:288
#0 Grav\Common\Grav:process in C:\wamp\www\grav\index.php:38

All grav pages in this install are giving me this error in web browser
I think it is odd that the admin plugin got the same error (admin should work if all else fails unless the php server itself is down). So that implies that one plugin (not the admin plugin) had the ability to break the functions of other plugins with pages that have nothing to do with that plugin.

https://www.dropbox.com/s/mp29bf042o24ypb/gravstrap%20plugin%20bad.zip?dl=1

Let me know if you need more files. I can zip/upload the entire grav install if needed to help reproduce the problem.
Github has issues with their uploader and zip files.

update meant lost of colors

With the update, the color tag do not work anymore. I understood that there is a need to create a new plugin from now on! May be a little bit to difficult for me though...
How show I do?

Disabling shortcode parser markdown

Hi @rhukster I'm developing a chart-shortcode and I have to disable markdown parser in my plugin. I discovered some public methods in ShortcodeManager class like setupMarkdown or processContent, I need it becouse I'm trying to "parse" json and/or yml data. Do you think is it suitable?

Assets are not added to page

Here's my shortcode:

class JumbotronShortcode extends Shortcode
{
public function init()
{
    $this->shortcode->getHandlers()->add('gravstrap-jumbotron', function(ShortcodeInterface $shortcode) {

        $this->shortcode->addAssets('css', 'plugin://gravstrap/css/gravstrap_jumbotron.css');

        $output = $this->twig->processTemplate('bootstrap/jumbotron.html.twig', [
            'id' => $shortcode->getParameter('id'),
            'image' => $shortcode->getParameter('image'),
            'fullwidth' => $shortcode->getParameter('fullwidth'),
            'content' => $shortcode->getContent(),
        ]);

        return $output;
    });
}
}

The 'plugin://gravstrap/css/gravstrap_jumbotron.css' asset is not added to page.

Proposal

Hi,
this is not an issue but a proposal, as the title suggests. :-)

I deeply deal with shortcodes these days and I made my Gravstrap plugin completely working using shortcodes, instead of using Yaml configuration to configure components.

I've abstracted the shortcode declaration and I'd like to ask you if you might consider to evaluate that work to be added to this plugin. Here's the directory where I implemented the base classes I'd like to add to shortcode-core plugin https://github.com/giansi/gravstrap/tree/shortcodes/classes/Base and here you will find an implementation example: https://github.com/giansi/gravstrap/tree/shortcodes/classes/Accordion.

Here it is how the plugin initializes the shortcodes: https://github.com/giansi/gravstrap/blob/shortcodes/gravstrap.php.

If you think this could be helpful for this plugin, I will port this piece of library to yours.

Can't nest shortcodes?

I can't seem to nest div's/shortcodes with this plugin?

[div class="row"]
[div class="x12 s12 m12 l12"]
## Header
[/div]
[/div]

Gives the following output HTML

<div class="row">
<div class="x12 s12 m12 l12">
</div>
<h2>Header:</h2>
</div>
[/div]

Expected result:

<div class="row">
<div class="x12 s12 m12 l12">
<h2>Header</h2>
</div>
</div>

After the last update plugin "kills" Gantry

Took me way to long as there was no error. When clicking on Gantry link I would just get

This site can’t be reached The connection was reset.

All the logs empty. So I decided to start turning off plugin by plugin and shorcode-core was the culprit.
Moment I disabled it Gantry started working ok. Tried restarting apache but it didn't work.

color syntax stopped working after last update

color syntax stopped working after last update and it seems not documented.
There is a shotcore-code.php but it does not seems to play its role anymore.
[color=#b52b27]《革命》って、必然的?[/color] do not work anymore.
What should I do?
Thanks in advance

Theme not receiving onShortcodeHandlers event

Hi, I am trying to add a shortcode to a theme but it doesn't seem to work – this is driving me crazy. This is my full theme code:

<?php
namespace Grav\Theme;
use Grav\Common\Theme;

class MyTheme extends Theme
{

    /**
     * Register events
     */
    public static function getSubscribedEvents()
    {
//        echo 'TEST'; exit; // this works, so the theme should be intialized.

        return [
            'onShortcodeHandlers' => ['onShortcodeHandlers', 0]
        ];
    }
    /**
     * Event that handles registering handler for shortcodes
     */
    public function onShortcodeHandlers()
    {
        // is never called?!
        $this->grav['shortcode']->registerShortcode('MyShortcode.php', __DIR__);
    }

}

Any ideas why this is?

Latest Update breaks section shortcode!

I just installed shortcode-core 2.3.1. Now the section shortcode isnt't rendered anymore. Reinstalled old section-shortcode.php and composer.json, everything is fine again???

Override parser

Is there a way for my shortcode plugin to override the shortcode-core parser setting? I tried just adding a parser setting to my config file, but that didn't do it. I'm having trouble with my new shortcode recognizing quoted parameters containing spaces.

Where to put custom shortcode files

I can't quite seem to figure out where to put a custom shortcode in order to get it working correctly. I tried creating a PHP file in the /user/custom/shortcodes folder, and as a standalone plugin. Either way I get the error:
Class 'Grav\Plugin\Shortcodes\Shortcode' not found

Could you perhaps provide the exact steps of where to put the files to create a simple shortcode?

Thank you.

Updating fontawesome?

Is it possible to override the version of font-awesome used by the shortcode core plugin?
Hopefully, so people can override the font-awesome version themselves in case they need to.
Something like a setting in a yaml file would be nice.

If this is not possible, could you please update font-awesome to version 5?
I would like to use an icon that doesn't yet exist in 4.

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.