Nossos voluntários ainda não traduziram este artigo para o Português (do Brasil) . Junte-se a nós e ajude a fazer o trabalho!
MDN supports turning sample code displayed in articles into running samples the reader can look at in action. These live samples can include HTML, CSS, and JavaScript in any combination.Note that "live" samples are not interactive; however, they do ensure that the output displayed for a sample matches the code of the sample exactly, because it is actually generated by the code sample.
How the live sample system works
The live sample system gathers up all the code in a group, merges it into one HTML file, and then renders that HTML in an <iframe>
. A live sample therefore consists of two pieces:
- A group of code blocks
- The macro call that (creates the frame or the link that) displays the result of the code blocks
A "group" of code blocks, in this context, is identified by the ID of a heading or a block element (such as a <div>
).
- If the ID belongs to a block element, the group includes all the code blocks within the enclosing block element whose ID is used.
- If the ID belongs to a heading, the group includes all the code blocks that are after that heading and before the next heading of the same heading level. Note that code blocks under subheadings of the specified heading are all used; if this is not the effect you want, use an ID on a block element instead.
The macro uses a special URL to fetch the sample code for a given group: https://url-of-page$samples/group-id
, where group-id
is the ID of the heading or block where the code is located. The resulting frame (or page) is sandboxed, secure, and technically may do anything that works on the Web. Of course, as a practical matter, the code must contribute to the point of the page that contains it; random stuff running on MDN will be removed by the editor community.
Note: You must use the macro for presenting the live sample's output. MDN's editor will strip out any direct use of the <iframe>
element in order to ensure security.
Each <pre>
block containing code for the sample has a class on it that indicates whether it's HTML, CSS, or JavaScript code; these are "brush: html", "brush: css", and "brush: js". These classes must be on the corresponding blocks of code so that the wiki can use them correctly; fortunately, these are added for you automatically when you use the syntax highlighter features in the editor's toolbar.
The live sample system has lots of options available, and we'll try to break things down to look at them a bit at a time.
Live sample macros
There are two macros that you can use to display live samples:
EmbedLiveSample
embeds a live sample into a pageLiveSampleLink
creates a link that opens the live sample in a new page
In many cases, you may be able to add the EmbedLiveSample
or LiveSampleLink
macro to pages with little or no additional work! As long as the sample can be identified by a heading's ID or is in a block with an ID you can use, simply adding the macro should do the job.
EmbedLiveSample macro
{{EmbedLiveSample(block_ID, width, height, screenshot_URL, page_slug)}}
- block_ID
- Required: The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
- width
- The width of the
<iframe>
to create, specified inpx
. This is optional; a reasonable default width will be used if you omit this. Note that if you want to use a specific width, you must also specify the height parameter. - height
- The height of the
<iframe>
to create, specified inpx
. This is optional; a reasonable default height will be used if you omit this. Note that if you want to use a specific height, you must also specify the width parameter. If you use only one of them, the default frame size is used. - screenshot_URL
- The URL of a screenshot that shows what the live sample should look like. This is optional, but can be useful for new technologies that may not work in the user's browser, so they can see what the sample would look like if it were supported by their browser. If you include this parameter, the screenshot is shown next to the live sample, with appropriate headings.
- page_slug
- The slug of the page containing the sample; this is optional, and if it's not provided, the sample is pulled from the same page on which the macro is used.
LiveSampleLink macro
{{LiveSampleLink(block_ID, link_text)}}
- block_ID
- The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
- link_text
- A string to use as the link text.
Using the live sample system
The sections below describe a few common use cases for the live sample system.
In all of these cases, to see the results of the live sample, you must click Save Changes in the editor (which takes you out of edit mode). Because of the reflexive, Inception-like nature of live samples, the Preview Changes functionality is not able to display live samples.
Turning snippets into live samples
One common use case is to take existing code snippets already shown on MDN and turn them into live samples.
Prepare the code samples
The first step is to either add code snippets or ensure that existing ones are ready to be used as live samples, in terms of the content and in terms of their mark-up. The code snippets, taken together, must comprise a complete, runnable example. For example, if the existing snippet shows only CSS, you might need to add a snippet of HTML for the CSS to operate on.
Each piece of code must be in a <pre>
block, with a separate block for each language, properly marked as to which language it is. Most of the time, this has already been done, but it's always worth double-checking to be sure each piece of code is configured with the correct syntax. Next to the PRE icon in the toolbar is a drop-down menu icon (tooltip: Syntax Highlighter) with the various languages that MDN does syntax highlighting for. Setting the language for the block for syntax highlighting also correlates it with a language for the purposes of the live sample system.
Note: You may have more than one block for each language; they are all concatenated together. This lets you have a chunk of code, followed by an explanation of how it works, then another chunk, and so forth. This makes it even easier to produce tutorials and the like that utilize live samples interspersed with explanatory text.
So make sure the <pre>
blocks for your HTML, CSS, and/or JavaScript code are each configured correctly for that language's syntax highlighting, and you're good to go.
Note: When pasting content into MDN, please be aware that if pasting styled content (including, for example, syntax highlighting in code being copied from another site) that you may be bringing along unwanted and unneeded additional styles or classes. Please be careful not to do this; if necessary, review your edit in source mode to remove these unnecessary styles and classes (or check it before pasting, or use the "Paste as plain text" option instead).
Insert the live sample macro
Once the code is in place and properly configured to identify each block's language, you need to insert the macro that creates the iframe.
- Click the Insert Live Code Sample iFrame button in the toolbar; it looks like this: . This opens a dialog box for configuring your live sample frame:
- Under Document, enter the title of the article that contains the sample you wish to embed. By default, it's the article you're currently editing, but you can choose an article elsewhere on MDN, too. This makes it possible to reuse samples on multiple pages if needed. (If you type new text in this field, a menu of partially matching pages appears; select the title of the page you want.)
- In the Sections in Document menu, select the section in the article that contains the code blocks of the sample you want to embed.
- Click the OK button to generate and insert the macro call that creates the sample frame for you. The macro call looks something like this:
{{ EmbedLiveSample('Live_sample_demo') }}
Adding a new live sample
If you're writing a new page, and want to insert code that you want to present as a live sample, even more of the work can be done for you by the editor!
- Click the Insert Code Sample Template button in the toolbar, which looks like this: . This presents a simple dialog asking you to name your live sample:
- Enter the title of the sample; this is used as the heading for the sample. Make sure that your title makes sense within the context of the page you're on.
- Click OK. A new heading with the title you entered is created, with sub-headings and empty code blocks for HTML, CSS, and JavaScript.
- Delete any headings and code blocks you don't need.
- Enter the code that makes up your sample in the appropriate code blocks
- Check conventions
Using the Sample Finder
As mentioned above, the Sample Finder is activated by clicking the Insert Live Code Sample iFrame icon. Unfortunately the the Sample Finder may produce a macro that is NOT usable without editing. There are two problem areas that should be carefully checked and edited if necessary.
- Document field. This field will search as you type and present a list of documents that match your string. But the list presented will NOT include the sub-page. For example, say you are working on the subpage for Negative under the main page @counter-style. The Sample Finder search will not find Negative but will find the main page @counter-style. When @counter-style is selected the field background turns green. See below for the issue this creates.
- Sections in Document. The pull-down menu Sections in Document may not show the section that you need. Just pick one, say Examples, and it can be fixed with a simple edit.
Here is what the Sample Finder produced:
{{ EmbedLiveSample('Examples', '', '', '', 'Web/CSS/@counter-style') }}
This macro will not work. The block_ID is Examples and it should be Example in this case (check the source ID for this section to verify which block_ID you need to use. Similarly the page_slug is @counter-style and it should be @counter-style/negative. These corrections can be done directly in the page with Edit active.
After editing the macro now looks like this:
{{ EmbedLiveSample('Example', '', '', '', 'Web/CSS/@counter-style/negative') }}
This edited macro will work correctly. If the macro is working correctly you will see the Open in CodePen button. A thumbnail of the example should appear above the Open in CodePen button. If the button is there but there isn't a thumbnail, just wait a few minutes. It may take some time for the server to generate it.
Finding samples that need updating
When looking for existing samples to update, there are three main kinds of updating you may wish to do:
- Turn an existing non-live example snippet into a live sample.
- Correct bugs in an existing live sample.
- Improve an existing live sample, or update a sample based on technology changes.
Note: If you find an article that has samples in need of being updated to use the live sample system, please add the tag "NeedsLiveSample" to the page.
Finding samples to turn into live samples
MDN has lots of older examples that don't yet use the live sample system. Our goal is to update most or all of these to be live samples. This will improve consistency and usability. You will almost certainly find many of these as you use MDN on a daily basis; however, how can you find them if you're specifically looking for them to update? Unfortunately, there's not an easy way to do that. But there are some guidelines you can follow to help track them down:
- Start by looking at this list of pages tagged with "NeedsLiveSample". These are pages that users have marked as needing updating. You should add this tag yourself, if you see a page that needs to be updated to use live samples but don't have time to fix right away.
- Browse through documentation trees that are likely to include examples, such as the JavaScript Guide, HTML documentation, and CSS reference.
- Search for terms like "example" or "sample" and look through the results for pages to update.
Live sample demo
This section is the result of using the live sample template button to create not only the main heading ("Live sample demo"), but also subheadings for our HTML, CSS, and JavaScript content. You're not limited to one block of each; in addition, they don't even need to be in any particular order. Mix and match!
You may choose to delete any of these you wish; if you don't need any script, just delete that heading and its <pre>
block. You can also delete the heading for a code block ("HTML", "CSS", or "JavaScript"), since these are not used by the live sample macro.
Now that the template has been inserted, we can put in some code, and even some explanatory text.
HTML
This HTML creates a paragraph and some blocks to help us position and style a message.
<p>A simple example of the live sample system in action.</p> <div class="box"> <div id="item">Hello world!</div> </div>
CSS
The CSS code styles the box as well as the text inside it.
.box { width: 200px; height: 100 px; border-radius: 6px; background-color: #ffaabb; } #item { width: 100%; font-weight: bold; text-align: center; font-size: 2em; }
JavaScript
This code is very simple. All it does is attach an event handler to the "Hello world!" text that makes an alert appear when it is clicked.
var el = document.getElementById('item'); el.onclick = function() { alert('Owww, stop poking me!'); }
Result
Here is the result of running the code blocks above via {{EmbedLiveSample('Live_sample_demo')}}
:
Here is a link that results from calling these code blocks via {{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}
:
Conventions regarding live samples
Note: This is currently (Feb. 2016) under discussion on the dev-mdc mailing list (see this thread). Any input is welcome. If this note persists after some month (Apr. 2016), please reach the author of the first email in this thread for updating this page.
- Orders of code blocks
- When adding a live sample, the code blocks should be sorted so that the first one corresponds to the main language for this sample (if there is one). For example, when adding a live sample for the HTML Reference, the first block should be HTML, when adding a live sample for the CSS Reference, it should be CSS and so on.
- Naming of headings
- When there is no ambiguity (e.g. the sample is under a "Examples" section), headings should be straightforward with the sole name of the corresponding language: HTML, CSS, JavaScript, SVG, etc. (see above). Headings like "HTML Content" or "JavaScript Content" should not be used. However if such a short heading makes content unclear, one can use a more thoughtful title.
- Using a "Result" block
- After the different code blocks, please use a last "Result" block before using the
EmbedLiveSample
macro (see above). This way, the semantic of the example is made clearer for both the reader and any tools that would parse the page (e.g. screen reader, web crawler).