△ Grav Shortcode Core Plugin

https://github.com/getgrav/grav-plugin-shortcode-core の README.md

About

Shortcode Core plugin は、WordPressBBCode で利用されている共通フォーマットを利用した、シンプルで強力なショート・コード・プラグインを開発することができます。コア・プラグインは、必要なライブラリをロードし、他のプラグインが使用できる新しいイベントを発生させます。 また、処理されたページのコンテンツがキャッシュされている場合でもショート・コードが効果的に動作するように、キャッシュされる CSS/JS アセットを追加する仕組みも提供します。 これにより、ショートコードは一度だけ処理され、すべてのページで不要な作業を行うことでパフォーマンスに影響を与えないようにします。

このプラグインは、Thunderer Advanced shortcode engine. を使用しています。詳しくは 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]

この例は、従来のマークダウンでは標準対応できない BBCode の機能を、Shortcode Core プラグインで提供しています。 構文が角括弧を使用した単純な開閉要素であることが分かると思います。

この例は、以下のようにレンダリングされます:

The core plugin required for any other shortcode specific plugin. Provides some basic BBCode style syntax such as underline, color, center, and size.
ショートコード固有のプラグインに必要なコアプラグインです。BBCode の基本的なスタイル構文(下線、色、中心、サイズなど)を提供します。

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

プラグインのコア設定を変更するには、プラグインから shortcode-core.yaml ファイルを user/config/plugins/ フォルダにコピーします(存在しない場合は作成します)。 そこで設定を変更することができます。

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

ページ単位でショートコードを有効にしたい場合があります。 これを実現するために、プラグインのデフォルトを設定します。

enabled: true
active: false

この設定により、プラグインは読み込まれますが、active にはなりません。次に、ショートコードを処理したいページで、これをページのヘッダーに追加するだけです。

ページ単位でショートコードを有効にしたい場合があります。 これを実現するために、プラグインのデフォルトを設定します。

shortcode-core:
    active: true

これにより、ショートコードはこのページのみで処理されるようになります。

また、以下のようにして、特定のページのパーサーを変更することができます。

shortcode-core:
    parser: regex

利用可能なショートコード

コアプラグインには、基本的なサンプルとして使用できる簡単なショートコードがいくつか含まれています。

下線

テキストの一部に下線を引く

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

フォント・サイズ

あるテキストのサイズを特定のピクセルサイズに設定する

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

左寄せ

ショートコードの間のテキストを左寄せにする

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

中央揃え

ショートコードの間のテキストを中央揃えにする

[center]This text is centered[/center]

右寄せ

このショートコードの間のテキストを右寄せにする

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

Div

マークダウンを idclasses 属性の両方をサポートする HTML の div タグで囲うようにする。

[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

HTLM の h1 から h6 タグに idclass 属性を追加できるようにします。

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

Span

マークダウンを idclasses 属性の両方をサポートする HTML の span タグで囲うようにする。

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

Columns

このショートコードは、強力な CSS カラムのサポートを利用できます。

[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]

デフォルトは2カラムです。 また、カラム分割のスタイルとして、 columns の数、 widthgaprule を設定することができる。

[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

電子メールアドレスをエンコードして、悪意のあるスクリプトが簡単に「スクレイピング」できないようにします。 これにはいくつかのオプションがあります。autolink は、メールをリンクに変換するためのオプションで、icon はメールの前に表示する font-awesome アイコンを選択するためのオプションで、subject はメールソフトに表示される件名を指定するためのオプションです。 すべての設定は任意です。

Safe-Email Address: [safe-email autolink="true" icon="envelope-o" subject="Feedback"]user@domain.com[/safe-email]

Section

section ショートコードは、マークダウンページのテキストを [section][/section] タグで囲み、後でアクセスできるように Grav にキャッシュさせる強力な方法です。 例えば、様々なセクションが記述されたページがあり、多くの chunks のデータを作成することができます。これらは、ショートコードオブジェクトの配列として Twig 追加されます。 この例として、次のようなマークダウンがあります。

[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]

これはページコンテンツから削除され、Twi g変数で利用できるようになるので、例えばカスタム HTML 構造にこれらを挿入することができます。

<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>

Section 情報を他のページから取得する

ページの contentMeta に格納されているショートコードを利用して、他のページからセクションを取得することもできます。

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

Notice

markdown-notices プラグインと同様の役割を果たす便利なショートコードで、http://learn.getgrav.orghttp://getgrav.org に見られるようなシンプルな通知ブロックを簡単に作成することができます。 使用するには、以下の構文を使用するだけです。

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

note, info, warning, tip タイプの中から、カラーオプションを選択することができます。

[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

HTMLの <mark></mark> タグはページ内のテキストをハイライトするのに非常に便利で、蛍光ペンのような役割を果たします。 しかし、HTML の中のマークダウンは処理されないため不便な場合があります。

もう一つの重要な使用例は、マークダウンのテキストブロック内のコードをハイライトすることです。

解決方法は簡単で、代わりにショートコード版を使用すればいいのです。

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

また、 class オプションを使用すると、 <mark> HTML タグに追加する CSS クラスを指定することができます (マークされた出力に色をつけるのに便利です)。

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

コードブロックでの使用も効果的です。

<?php
class Pipeline extends PropertyObject
{
    use AssetUtilsTrait;

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

    ...
}

オプションの style 属性を block に渡すと、全行がハイライトされるようになります。

<?php
class Pipeline extends PropertyObject
{
    use AssetUtilsTrait;

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

    ...
}

Language

Grav の多言語機能をフックして、現在アクティブな言語に対してのみ、特定のブロックを表示できるようにします。

[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.

すべてのショートコードを表示する

CLI コマンドで、利用可能なショートコードをすべて表示できるようになりました。

bin/plugin shortcode-core display