Skip to content

Latest commit

 

History

History
127 lines (79 loc) · 2.32 KB

8.Shortcode.md

File metadata and controls

127 lines (79 loc) · 2.32 KB

Shortcode

Shortcode helps you to build content dynamically, for example you can put list of link to feature post in your post content, or you can embed video, content that editor does not support.

Use shortcode

Shortcode syntax:

  • Inline: [[shortcode_name arg1, arg2 /]]

  • Pair shortcode

    [[shortcode_name arg1, arg2, arg3]]
    content here
    ...
    [[/shortcode_name]]
    
  • Before render post/page content, call compile_shortcode() function to compile all shortcode to html

Built-in shortcode

There are currently 3 built-in shortcode

  • youtube to embed youtube video

    [[youtube "NBEqAzl7Xus"/]]

    compiled to

    <div class="embed video-player">
        <iframe class="youtube-player" type="text/html" width="640" height="385" src="https://www.youtube.com/embed/NBEqAzl7Xus" allowfullscreen frameborder="0">
        </iframe>
    </div>
  • vimeo to embed Vimeo video

    [[vimeo "369696354"/]]
    
  • gist to embed your Gist

    [[gist "3e6d628eadcc32a6793470ce2775c14c"/]]
    

Define your own shortcode

Shortcode must be define in your_theme/views/shortcode_view.ex or add a template to directory your_theme/templates/shortcode/

Define shortcode in view

This is source code to define youtube shortcode

def render_shortcode("youtube", %{args: [video_id]}) do
    """
    <div class="embed video-player">
    <iframe class="youtube-player" type="text/html" width="640" height="385" src="https://www.youtube.com/embed/#{
      video_id
    }" allowfullscreen frameborder="0">
    </iframe>
    </div>
    """
  end

All arguments passed to shortcode can be access via key args

Use shortcode

[[youtube "video_id"/]]

Define shortcode in template

You simply create a template file, file name is used as shortcode name.

Example

Create a file your_theme/templates/shortcode/my_shortcode.html.eex

<h1> Hello <%= List.first(@args) %>!</h1>

Use shortcode:

[[my_shortcode "John"/]]

Pair shortcode

For pair shortcode, content between open and close tag can be access via key inner_content

Example

[[pair_shortcode]]
this is inner content
[[/pair_shortcode]]
def render("pair_shortcode", %{inner_content: content} = assigns) do
# do something you want with content
end