diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-br/mdn/tools | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/pt-br/mdn/tools')
4 files changed, 610 insertions, 0 deletions
diff --git a/files/pt-br/mdn/tools/index.html b/files/pt-br/mdn/tools/index.html new file mode 100644 index 0000000000..a8482f8751 --- /dev/null +++ b/files/pt-br/mdn/tools/index.html @@ -0,0 +1,15 @@ +--- +title: Ferramentas do MDN +slug: MDN/Tools +tags: + - Landing + - MDN Meta +translation_of: MDN/Tools +--- +<div>{{MDNSidebar}}</div> + +<div>{{IncludeSubnav("/pt-BR/docs/MDN")}}</div> + +<p>MDN oferece ferramentas tornando fácil o acompanhamento do progresso, gerenciamento de conteúdo e manter o site com as últimas atualizações.</p> + +<p>{{LandingPageListSubpages}}</p> diff --git a/files/pt-br/mdn/tools/kumascript/index.html b/files/pt-br/mdn/tools/kumascript/index.html new file mode 100644 index 0000000000..9c89712e59 --- /dev/null +++ b/files/pt-br/mdn/tools/kumascript/index.html @@ -0,0 +1,500 @@ +--- +title: KumaScript +slug: MDN/Tools/KumaScript +tags: + - Guide + - Kuma + - KumaScript + - MDN Meta + - NeedsContent + - NeedsTranslation + - Site-wide + - Tools + - TopicStub +translation_of: MDN/Tools/KumaScript +--- +<div>{{MDNSidebar}}</div><h2 id="Overview">Overview</h2> + +<p><span class="seoSummary">On the <a href="/en-US/docs/MDN/Kuma">Kuma</a> platform that powers MDN, the template system for automating aspects of content on the wiki is called <a class="link-https" href="https://github.com/mdn/kumascript" title="https://github.com/mdn/kumascript">KumaScript</a>. KumaScript is powered by server-side JavaScript, implemented using <a class="external" href="https://nodejs.org/en/" title="https://nodejs.org/en/">Node.js</a>.</span> This article provides basic information on how to use KumaScript.</p> + +<p>For a detailed overview and Q&A of KumaScript, watch the MDN dev team's <a href="https://vreplay.mozilla.com/replay/showRecordDetails.html?sortBy=date&viewCount=1&currentPage=1&groupBy=combo&roomFilter=&usernameFilter=&searchFilter=&usernameFullFilter=&myManager=-1&adminManager=0&webCast=0&command=&recId=1082&auxMessage=&auxMessage1=&lang=en&langChanged=&tenantFilter=&securityTab=">KumaScript Fireside Chat</a> (the meeting starts at 10 minutes into the video). KumaScript replaced DekiScript, which was the template language for MindTouch, the previous platform used by MDN.</p> + +<h3 id="What_is_KumaScript">What is KumaScript?</h3> + +<ul> + <li>A way to reuse and localize content that appears repeatedly between documents (e.g., compatibility labels, section navigation, warning banners).</li> + <li>A way to build documents out of content pulled from other documents.</li> + <li>A way to fetch and include content from other web sites and services (e.g., Bugzilla).</li> +</ul> + +<h3 id="What_KumaScript_is_not">What KumaScript is not</h3> + +<ul> + <li>KumaScript does not support interactive scripting of the kind that can accept form submissions.</li> + <li>KumaScript does not have access to a database, files, or any other way to store information persistently.</li> + <li>KumaScript does not support site personalization based on the user currently logged in.</li> + <li>KumaScript does not have access to user information, only to the content and metadata of a wiki page being viewed.</li> +</ul> + +<h2 id="Basics">Basics</h2> + +<p>KumaScript is used on MDN in <a class="link-https" href="https://github.com/visionmedia/ejs" title="https://github.com/visionmedia/ejs">embedded JavaScript templates</a>. These templates can be invoked in document content by any MDN author, through the use of macros.</p> + +<p>A script in KumaScript is a <em>template</em>, and each template is a file in <a href="https://github.com/mdn/kumascript/tree/master/macros">the macros directory of the KumaScript repository</a> on Github. A <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/hello.ejs" title="hello.ejs">template</a> looks like this:</p> + +<pre class="notranslate"><% for (var i = 0; i < $0; i++) { %> +Hello #<%= i %> +<% } %></pre> + +<p>Invoking a template is done with a <em>macro</em>, which can be used anywhere in any wiki content. A macro looks like this:</p> + +<pre class="notranslate">\{{ hello("3") }}</pre> + +<p>The output of the macro looks like this:</p> + +<pre class="notranslate">Hello #0 +Hello #1 +Hello #2</pre> + +<h3 id="Macro_syntax">Macro syntax</h3> + +<p>KumaScript templates are invoked in document content with macros, like this:</p> + +<pre class="notranslate">\{{ templateName("arg0", "arg1", ..., "argN") }} +</pre> + +<p>Macro syntax consists of these rules:</p> + +<ul> + <li>Macros start and end with <code>\{{</code> and <code>\}}</code> characters.</li> + <li>The first part of the macro is the name of a template. The lowercase value of this name should match the lowercase value of one of the filenames under <a href="https://github.com/mdn/kumascript/tree/master/macros">the macros directory of KumaScript</a>.</li> + <li>A template can accept parameters, and this parameter list starts and ends with parentheses.</li> + <li>All non-numeric parameters must be in quotes. Numbers can be left unquoted.</li> +</ul> + +<h4 id="Using_JSON_as_a_macro_parameter">Using JSON as a macro parameter</h4> + +<p>As a semi-experimental feature (not guaranteed to work), you can supply a JSON object for the first and only parameter, like so:</p> + +<pre class="notranslate">\{{ templateName({ "Alpha":"one", "Beta":["a","b","c"], "Foo":"http:\/\/mozilla.org\/" }) }} +</pre> + +<p>The data from this macro is available in template code as an object in the <code>$0</code> argument (e.g., <code>$0.Alpha</code>, <code>$0.Beta</code>, <code>$0.Foo</code>). This also allows you to express complex data structures in macro parameters that are hard or impossible to do with a simple list of parameters.</p> + +<p>Note that this parameter style is very picky — it must adhere to <a href="http://json.org/" title="http://json.org/">JSON syntax</a> exactly, which has some requirements about escaping characters that are easy to miss (e.g., all forward slashes are escaped). When in doubt, <a href="http://jsonlint.com/" title="http://jsonlint.com/">try running your JSON through a validator</a>.</p> + +<h4 id="How_to_write_in_text">How to write "\{{" in text</h4> + +<p>Since the character sequence "<code>\{{</code>" is used to indicate the start of a macro, this can be troublesome if you actually just want to use "<code>\{{</code>" and "<code>}}</code>" in a page. It will probably produce <code>DocumentParsingError</code> messages.</p> + +<p>In this case, you can escape the first brace with a backslash, like so: <code>\\{</code></p> + +<h3 id="Template_syntax">Template syntax</h3> + +<p>Each KumaScript template is a file under <a href="https://github.com/mdn/kumascript/tree/master/macros">the macros directory of KumaScript</a>. You create and edit these files as you would the files of any open-source project on GitHub (see <a href="https://github.com/mdn/kumascript">the KumaScript README</a> for more information).</p> + +<p>KumaScript templates are processed by an <a class="link-https" href="https://github.com/visionmedia/ejs" title="https://github.com/visionmedia/ejs">embedded JavaScript template engine</a> with a few simple rules:</p> + +<ul> + <li>Within a template, the parameters passed in from the macro are available as the variables <code>$0</code>, <code>$1</code>, <code>$2</code>, and so on. The entire list of parameters is also available in a template as the variable <code>arguments</code>.</li> + <li>Most text is treated as output and included in the output stream.</li> + <li>JavaScript variables and expressions can be inserted into the output stream with these blocks: + <ul> + <li><code><%= expr %></code> — the value of a JavaScript expression is escaped for HTML before being included in output (e.g., characters like <code><</code> and <code>></code> are turned into <code>&lt;</code> and <code>&gt;</code>).</li> + <li><code><%- expr %></code> — the value of a JavaScript expression is included in output without any escaping. (Use this if you want to dynamically build markup or use the results of another template that may include markup.)</li> + <li>It is an error to include semicolons inside these blocks.</li> + </ul> + </li> + <li>Anything inside a <code><% %></code> block is interpreted as JavaScript. This can include loops, conditionals, etc.</li> + <li>Nothing inside a <code><% %></code> block can ever contribute to the output stream. But, you can transition from JS mode to output mode using <code><% %></code>—for example: + <pre class="notranslate"><% for (var i = 0; i < $0; i++) { %> +Hello #<%= i %> +<% } %> +</pre> + + <p>Note how the JavaScript code is contained in <code><% ... %></code>, and output happens in the space between <code>%> ... <%</code>. The <code>for</code> loop in JS can begin with one <code><% %></code> block, transition to output mode, and finish up in a second <code><% %></code> JS block.</p> + </li> + <li>For more details on EJS syntax, <a class="link-https" href="https://github.com/visionmedia/ejs" title="https://github.com/visionmedia/ejs">check out the upstream module documentation</a>.</li> +</ul> + +<h3 id="Tips">Tips</h3> + +<p>You can see a list of macros and how they are used on MDN on the <a href="/en-US/dashboards/macros">macros dashboard</a>.</p> + +<h2 id="Advanced_Features">Advanced Features</h2> + +<p>Beyond the basics, the KumaScript system offers some advanced features.</p> + +<h3 id="Environment_variables">Environment variables</h3> + +<p>When the wiki makes a call to the KumaScript service, it passes along some context on the current document that KumaScript makes available to templates as variables:</p> + +<dl> + <dt><code>env.path</code></dt> + <dd>The path to the current wiki document</dd> + <dt><code>env.url</code></dt> + <dd>The full URL to the current wiki document</dd> + <dt><code>env.id</code></dt> + <dd>A short, unique ID for the current wiki document</dd> + <dt><code>env.files</code></dt> + <dd>An array of the files attached to the current wiki document; each object in the array is as described under {{ anch("File objects") }} below</dd> + <dt><code>env.review_tags</code></dt> + <dd>An array of the review tags on the article ("technical", "editorial", etc.)</dd> + <dt><code>env.locale</code></dt> + <dd>The locale of the current wiki document</dd> + <dt><code>env.title</code></dt> + <dd>The title of the current wiki document</dd> + <dt><code>env.slug</code></dt> + <dd>The URL slug of the current wiki document</dd> + <dt><code>env.tags</code></dt> + <dd>An array list of tag names for the current wiki document</dd> + <dt><code>env.modified</code></dt> + <dd>Last modified timestamp for the current wiki document</dd> + <dt><code>env.cache_control</code></dt> + <dd><code>Cache-Control</code> header sent in the request for the current wiki document, useful in deciding whether to invalidate caches</dd> +</dl> + +<h4 id="File_objects">File objects</h4> + +<p>Each file object has the following fields:</p> + +<dl> + <dt><code>title</code></dt> + <dd>The attachment's title</dd> + <dt><code>description</code></dt> + <dd>A textual description of the current revision of the file</dd> + <dt><code>filename</code></dt> + <dd>The file's name</dd> + <dt><code>size</code></dt> + <dd>The size of the file in bytes</dd> + <dt><code>author</code></dt> + <dd>The username of the person who uploaded the file</dd> + <dt><code>mime</code></dt> + <dd>The MIME type of the file</dd> + <dt><code>url</code></dt> + <dd>The URL at which the file can be found</dd> +</dl> + +<h4 id="Working_with_tag_lists">Working with tag lists</h4> + +<p>The <code>env.tags</code> and <code>env.review_tags</code> variables return arrays of tags. You can work with these in many ways, of course, but here are a couple of suggestions.</p> + +<h5 id="Looking_to_see_if_a_specific_tag_is_set">Looking to see if a specific tag is set</h5> + +<p>You can look to see if a specific tag exists on a page like this:</p> + +<pre class="brush: js notranslate">if (env.tags.indexOf("tag") != −1) { + // The page has the tag "tag" +} +</pre> + +<h5 id="Iterating_over_all_the_tags_on_a_page">Iterating over all the tags on a page</h5> + +<p>You can also iterate over all the tags on a page, like this:</p> + +<pre class="brush: js notranslate">env.tag.forEach(function(tag) { + // do whatever you need to do, such as: + if (tag.indexOf("a") == 0) { + // this tag starts with "a" - woohoo! + } +});</pre> + +<h3 id="APIs_and_Modules">APIs and Modules</h3> + +<p>KumaScript offers some built-in methods and APIs for KumaScript macros. Macros can also use <code>module.exports</code> to export new API methods.</p> + +<p>API changes require updating the KumaScript engine or macros via a pull request to the <a href="https://github.com/mdn/kumascript">KumaScript repository</a>.</p> + +<h4 id="Built-in_methods">Built-in methods</h4> + +<p>This manually-maintained documentation is likely to fall out of date with the code. With that in mind, <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/lib/kumascript/api.js#L175" title="https://github.com/mdn/kumascript/blob/master/lib/kumascript/api.js#L208">you can always check out the latest state of built-in APIs in the KumaScript source</a>. But here is a selection of useful methods exposed to templates:</p> + +<dl> + <dt><code>md5(string)</code></dt> + <dd>Returns an MD5 hex digest of the given string.</dd> + <dt><code>template("name", ["arg0", "arg1", ..., "argN"])</code></dt> + <dd>Executes and returns the result of the named template with the given list of parameters.</dd> + <dd>Example: <code><%- template("warning", ["foo", "bar", "baz"]) %></code>.</dd> + <dd>Example using the <code>domxref</code> macro: <code><%- template("domxref", ["Event.bubbles", "bubbles"]) %></code>.</dd> + <dd>This is a JavaScript function. So, if one of the parameters is an arg variable like $2, do not put it in quotes. Like this: <code><%- template("warning", [$1, $2, "baz"]) %></code>. If you need to call another template from within a block of code, do not use <code><%</code> ... <code>%></code>. Example: <code>myvar = "<li>" + template("LXRSearch", ["ident", "i", $1]) + "</li>";</code></dd> + <dt><code>require(name)</code></dt> + <dd>Loads another template as a module; any output is ignored. Anything assigned to <code>module.exports</code> in the template is returned.</dd> + <dd>Used in templates like so: <code><% var my_module = require('MyModule'); %></code>.</dd> + <dt><code>cacheFn(key, timeout, function_to_cache)</code></dt> + <dd>Using the given key and cache entry lifetime, cache the results of the given function. Honors the value of <code>env.cache_control</code> to invalidate cache on <code>no-cache</code>, which can be sent by a logged-in user hitting shift-refresh.</dd> + <dt><code>request</code></dt> + <dd>Access to <a class="link-https" href="https://github.com/mikeal/request" title="https://github.com/mikeal/request"><code>mikeal/request</code></a>, a library for making HTTP requests. Using this module in KumaScript templates is not yet very friendly, so you may want to wrap usage in module APIs that simplify things.</dd> + <dt><code>log.debug(string)</code></dt> + <dd>Outputs a debug message into the script log on the page (i.e. the big red box that usually displays errors).</dd> +</dl> + +<h4 id="Built-in_API_modules">Built-in API modules</h4> + +<p>There's only one API built in at the moment, in the <code>kuma</code> namespace. You can see the most up to date list of methods under <code>kuma</code> from <a href="https://github.com/mdn/kumascript/blob/master/lib/kumascript/api.js#L74">the KumaScript source code</a>, but here are a few:</p> + +<dl> + <dt><code>kuma.inspect(object)</code></dt> + <dd>Renders any JS object as a string, handy for use with <code>log.debug()</code>. See also: <a href="http://nodejs.org/api/util.html#util_util_inspect_object_options">node.js <code>util.inspect()</code></a>.</dd> +</dl> + +<dl> + <dt><code>kuma.htmlEscape(string)</code></dt> + <dd>Escapes the characters <code>&, <, >, "</code> to <code>&amp, &lt;, &gt;, &quot;</code>, respectively.</dd> + <dt><code>kuma.url</code></dt> + <dd>See also: <a href="http://nodejs.org/api/url.html">node.js <code>url</code> module</a>.</dd> + <dt><code>kuma.fetchFeed(url)</code></dt> + <dd>Fetch an RSS feed and parse it into a JS object. See also: <a href="https://github.com/mdn/kumascript/blob/master/macros/InsertFeedLinkList.ejs"><code>InsertFeedLinkList</code></a></dd> +</dl> + +<h4 id="Creating_modules">Creating modules</h4> + +<p>Using the built-in <code>require()</code> method, you can load a template as a module to share common variables and methods between templates. A module can be defined in a template like this:</p> + +<pre class="notranslate"><% +module.exports = { + add: function (a, b) { + return a + b; + } +} +%> +</pre> + +<p>Assuming this template is saved under <a href="https://github.com/mdn/kumascript/tree/master/macros">https://github.com/mdn/kumascript/tree/master/macros</a> as <code>MathLib.ejs</code>, you can use it in another template like so:</p> + +<pre class="notranslate"><% +var math_lib = require("MathLib"); +%> +The result of 2 + 2 = <%= math_lib.add(2, 2) %> +</pre> + +<p>And, the output of this template will be:</p> + +<pre class="notranslate">The result of 2 + 2 = 4 +</pre> + +<h4 id="Auto-loaded_modules">Auto-loaded modules</h4> + +<p>There are a set of modules editable as wiki templates that are automatically loaded and made available to every template. This set is defined in the configuration file for the KumaScript service - any changes to this requires an IT bug to edit configuration and a restart of the service.</p> + +<p>For the most part, these attempt to provide stand-ins for legacy DekiScript features to ease template migration. But, going forward, these can be used to share common variables and methods between templates:</p> + +<ul> + <li><code>mdn.*</code> - <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/MDN-Common.ejs" title="MDN:Common">MDN-Common</a></li> + <li><code>Page.*</code> - <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Page.ejs" title="DekiScript:Page">DekiScript-Page</a></li> + <li><code>String.*</code> - <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/DekiScript-String.ejs" title="DekiScript:String">DekiScript-String</a></li> + <li><code>Uri.*</code> - <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Uri.ejs" title="DekiScript:Uri">DekiScript-Uri</a></li> + <li><code>Web.*</code> - <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Web.ejs" title="DekiScript:Web">DekiScript-Web</a></li> + <li><code>Wiki.*</code> - <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Wiki.ejs" title="DekiScript:Wiki">DekiScript-Wiki</a></li> +</ul> + +<p><strong>Note:</strong> You might notice that the DekiScript modules use a built-in method named <code>buildAPI()</code>, like so:</p> + +<pre class="notranslate"><% module.exports = buildAPI({ + StartsWith: function (str, sub_str) { + return (''+str).indexOf(sub_str) === 0; + } +}); %> +</pre> + +<p>The reason for this is because DekiScript is case-insensitive when it comes to references to API methods, whereas JavaScript is strict about uppercase and lowercase in references. So, <code>buildAPI()</code> is a hack to try to cover common case variations in DekiScript calls found in legacy templates.</p> + +<div class="note"> +<p>With that in mind, please do not use <code>buildAPI()</code> in new modules.</p> +</div> + +<h2 id="Tips_and_caveats">Tips and caveats</h2> + +<h3 id="Debugging">Debugging</h3> + +<p>A useful tip when debugging. You can use the <code>log.debug()</code> method to output text to the scripting messages area at the top of the page that's running your template. Note that you need to be really sure to remove these when you're done debugging, as they're visible to all users! To use it, just do something like this:</p> + +<pre class="notranslate"><%- log.debug("Some text goes here"); %> +</pre> + +<p>You can, of course, create more complex output using script code if it's helpful.</p> + +<h3 id="Caching">Caching</h3> + +<p>KumaScript templates are heavily cached to improve performance. For the most part, this works great to serve up content that doesn't change very often. But, as a logged-in user, you have two options to force a page to be regenerated, in case you notice issues with scripting:</p> + +<ul> + <li>Hit Refresh in your browser. This causes KumaScript to invalidate its cache for the content on the current page by issuing a request with a <code>Cache-Control: max-age=0</code> header.</li> + <li>Hit Shift-Refresh in your browser. This causes KumaScript to invalidate cache for the current page, as well as for any templates or content used by the current page by issuing a request with a <code>Cache-Control: no-cache</code> header.</li> +</ul> + +<h3 id="Using_search_keywords_to_open_template_pages">Using search keywords to open template pages</h3> + +<p>When using templates, it's common to open the template's code in a browser window to review the comments at the top, which are used to document the template, its parameters, and how to use it properly. To quickly access templates, you can create a Firefox <a href="http://kb.mozillazine.org/Using_keyword_searches">search keyword</a>, which gives you a shortcut you can type in the URL box to get to a template more easily.</p> + +<p>To create a search keyword, open the bookmarks window by choosing "Show all bookmarks" in the Bookmarks menu, or by pressing <kbd>Control</kbd>-<kbd>Shift</kbd>-<kbd>B</kbd> (<kbd>Command</kbd>-<kbd>Shift</kbd>-<kbd>B</kbd> on Mac). Then from the utility ("Gear") menu in the Library window that appears, choose "New Bookmark...".</p> + +<p>This causes the bookmark editing dialog to appear. Fill that out as follows:</p> + +<dl> + <dt>Name</dt> + <dd>A suitable name for your search keyword; "Open MDN Template" is a good one.</dd> + <dt>Location</dt> + <dd><kbd>https://github.com/mdn/kumascript/blob/master/macros/%s</kbd></dd> + <dt>Tags {{optional_inline}}</dt> + <dd>A list of tags used to organize your bookmarks; these are entirely optional and what (if any) tags you use is up to you.</dd> + <dt>Keyword</dt> + <dd>The shortcut text you wish to use to access the template. Ideally, this should be something short and quick to type, such as simply "t" or "mdnt".</dd> + <dt>Description {{optional_inline}}</dt> + <dd>A suitable description explaining what the search keyword does.</dd> +</dl> + +<p>The resulting dialog looks something like this:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14432/Screen%20Shot%202016-11-28%20at%203.08.39%20PM.png" style="height: 289px; width: 500px;"></p> + +<p>Then click the "Add" button to save your new search keyword. From then on, typing your keyword, then a space, then the name of a macro will open that macro in your current tab. So if you used "t" as the keyword, typing <kbd>t ListSubpages</kbd> will show you the page at {{TemplateLink("ListSubpages")}}.</p> + +<h2 id="Cookbook">Cookbook</h2> + +<p>This section will list examples of common patterns for templates used on MDN, including samples of legacy DekiScript templates and their new KumaScript equivalents.</p> + +<h3 id="Force_templates_used_on_a_page_to_be_reloaded">Force templates used on a page to be reloaded</h3> + +<p>It bears repeating: To force templates used on a page to be reloaded after editing, hit Shift-Reload. Just using Reload by itself will cause the page contents to be regenerated, but using cached templates and included content. A Shift-Reload is necessary to invalidate caches beyond just the content of the page itself.</p> + +<h3 id="Recovering_from_Unknown_Error">Recovering from "Unknown Error"</h3> + +<p>Sometimes, you'll see a scripting message like this when you load a page:</p> + +<pre class="notranslate">Kumascript service failed unexpectedly: <class 'httplib.BadStatusLine'></pre> + +<p>This is probably a temporary failure of the KumaScript service. If you Refresh the page, the error may disappear. If that doesn't work, try a Shift-Refresh. If, after a few tries, the error persists - <a class="link-https" href="https://bugzilla.mozilla.org/enter_bug.cgi?product=mozilla.org&format=itrequest">file an IT bug</a> for Mozilla Developer Network to ask for an investigation.</p> + +<h3 id="Broken_wiki.languages_macros">Broken wiki.languages() macros</h3> + +<p>On some pages, you'll see a scripting error like this:</p> + +<pre class="notranslate">Syntax error at line 436, column 461: Expected valid JSON object as the parameter of the preceding macro but... +</pre> + +<p>If you edit the page, you'll probably see a macro like this at the bottom of the page:</p> + +<pre class="notranslate">\{{ wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) }} +</pre> + +<p>To fix the problem, just delete the macro. Or, replace the curly braces on either side with HTML comments <code><!-- --></code> to preserve the information, like so:</p> + +<pre class="notranslate"><!-- wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) --> +</pre> + +<p>Because Kuma supports localization differently, these macros aren't actually needed any more. But, they've been left intact in case we need to revisit the relationships between localized pages. Unfortunately, it seems like migration has failed to convert some of them properly.</p> + +<h3 id="Finding_the_Current_Pages_Language">Finding the Current Page's Language</h3> + +<p>In KumaScript, the locale of the current document is exposed as an environment variable:</p> + +<pre class="notranslate">var lang = env.locale; +</pre> + +<p>The <code>env.locale</code> variable should be reliable and defined for every document.</p> + +<h3 id="Reading_the_contents_of_a_page_attachment">Reading the contents of a page attachment</h3> + +<p>You can read the contents of an attached file by using the <code>mdn.getFileContent()</code> function, like this:</p> + +<pre class="notranslate"><% + var contents = mdn.getFileContent(fileUrl); + ... do stuff with the contents ... +%> +</pre> + +<p>or</p> + +<pre class="notranslate"><%-mdn.getFileContent(fileObject)%> +</pre> + +<p>In other words, you may specify either the URL of the file to read or as a file object. The file objects for a page can be accessed through the array <code>env.files</code>. So, for example, to embed the contents of the first file attached to the article, you can do this:</p> + +<pre class="notranslate"><%-mdn.getFileContent(env.files[0])%> +</pre> + +<div class="note"><strong>Note:</strong> You probably don't want to try to embed the contents of a non-text file this way, as the raw contents would be injected as text. This is meant to let you access the contents of text attachments.</div> + +<p>If the file isn't found, an empty string is returned. There is currently no way to tell the difference between an empty file and a nonexistent one. But if you're putting empty files on the wiki, you're doing it wrong.</p> + +<h3 id="Localizing_template_content">Localizing template content</h3> + +<p>Templates are not translated like wiki pages, rather any single template might be used for any number of locales.</p> + +<p>So the main way to output content tailored to the current document locale is to pivot on the value of <code>env.locale</code>. There are many ways to do this, but a few patterns are common in the conversion of legacy DekiScript templates:</p> + +<h4 id="Ifelse_blocks_in_KumaScript">If/else blocks in KumaScript</h4> + +<p>The KumaScript equivalent of this can be achieved with simple if/else blocks, like so:</p> + +<pre class="notranslate"><% if ("fr" == env.locale) { %> +<%- template("CSSRef") %> « <a title="Référence_CSS/Extensions_Mozilla" href="/fr/docs/Référence_CSS/Extensions_Mozilla">Référence CSS:Extensions Mozilla</a> +<% } else if ("ja" == env.locale) { %> +<%- template("CSSRef") %> « <a title="CSS_Reference/Mozilla_Extensions" href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS リファレンス:Mozilla 拡張仕様</a> +<% } else if ("pl" == env.locale) { %> +<%- template("CSSRef") %> « <a title="Dokumentacja_CSS/Rozszerzenia_Mozilli" href="/pl/docs/Dokumentacja_CSS/Rozszerzenia_Mozilli">Dokumentacja CSS:Rozszerzenia Mozilli</a> +<% } else if ("de" == env.locale) { %> +<%- template("CSSRef") %> « <a title="CSS_Referenz/Mozilla_CSS_Erweiterungen" href="/de/docs/CSS_Referenz/Mozilla_CSS_Erweiterungen">CSS Referenz: Mozilla Erweiterungen</a> +<% } else { %> +<%- template("CSSRef") %> « <a title="CSS_Reference/Mozilla_Extensions" href="/en-US/docs/CSS_Reference/Mozilla_Extensions">CSS Reference:Mozilla Extensions</a> +<% } %> +</pre> + +<p>Depending on what text editor is your favorite, you may be able to copy & paste from the browser-based editor and attack this pattern with a series of search/replace regexes to get you most of the way there.</p> + +<p>My favorite editor is MacVim, and a series of regexes like this does the bulk of the work with just a little manual clean up following:</p> + +<pre class="notranslate">%s#<span#^M<span#g +%s#<span lang="\(.*\)" .*>#<% } else if ("\1" == env.locale) { %>#g +%s#<span class="script">template.Cssxref(#<%- template("Cssxref", [# +%s#)</span> </span>#]) %> +</pre> + +<p>Your mileage may vary, and patterns change slightly from template to template. That's why the migration script was unable to just handle this automatically, after all.</p> + +<h4 id="String_variables_and_switch">String variables and switch</h4> + +<p>Rather than switch between full chunks of markup, you can define a set of strings, switch them based on locale, and then use them to fill in placeholders in a single chunk of markup:</p> + +<pre class="notranslate"><% +var s_title = 'Firefox for Developers'; +switch (env.locale) { + case 'de': + s_title = "Firefox für Entwickler"; + break; + case 'fr': + s_title = "Firefox pour les développeurs"; + break; + case 'es': + s_title = "Firefox para desarrolladores"; + break; +}; +%> +<span class="title"><%= s_title %></span> +</pre> + +<h4 id="Use_mdn.localString">Use <code>mdn.localString()</code></h4> + +<p>A recent addition to the <code>MDN:Common</code> module is <code>mdn.localString()</code>, used like this:</p> + +<pre class="notranslate"><% +var s_title = mdn.localString({ + "en-US": "Firefox for Developers", + "de": "Firefox für Entwickler", + "es": "Firefox para desarrolladores" +}); +%> +<span class="title"><%= s_title %></span> +</pre> + +<p>This is more concise than the switch statement, and may be a better choice where a single string is concerned. However, if many strings need to be translated (e.g., as in <a class="link-https" href="https://github.com/mdn/kumascript/blob/master/macros/CSSRef.ejs" title="CSSRef">CSSRef</a>), a switch statement might help keep all the strings grouped by locale and more easily translated that way.</p> + +<p>When the object does not have the appropriate locale, the value of "en-US" is used as the initial value.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="http://kuma.readthedocs.io/en/latest/" title="Getting started with Kuma">Getting started with Kuma</a></li> + <li><a href="https://github.com/mdn/kumascript" title="Project:en/KumaScript reference">KumaScript reference</a></li> + <li><a class="link-https" href="https://wiki.mozilla.org/MDN/Kuma" title="https://wiki.mozilla.org/MDN/Kuma">Kuma wiki</a></li> +</ul> diff --git a/files/pt-br/mdn/tools/kumascript/solucionando_problemas_de_erros_de_kumascript/index.html b/files/pt-br/mdn/tools/kumascript/solucionando_problemas_de_erros_de_kumascript/index.html new file mode 100644 index 0000000000..56053d6468 --- /dev/null +++ b/files/pt-br/mdn/tools/kumascript/solucionando_problemas_de_erros_de_kumascript/index.html @@ -0,0 +1,63 @@ +--- +title: Solucionando problemas de erros de KumaScript +slug: MDN/Tools/KumaScript/Solucionando_problemas_de_erros_de_KumaScript +tags: + - Erros + - Ferramentas + - Guía + - KumaScript + - MDN Meta +translation_of: MDN/Tools/KumaScript/Troubleshooting +--- +<div>{{MDNSidebar}}</div><div class="summary"> +<p>Erros de <a href="/en-US/docs/MDN/Kuma/Introduction_to_KumaScript">KumaScript</a> aparecendo numa página podem ser muito desagradáveis aos leitores, mostrando grandes e medonhas caixas vermelhas, mas felizmente qualquer pessoa com uma conta MDN pode editar um documento e consertar tais tipos de erros. Quando uma página possui algum erro, ela é adicionada na lista de <a href="/docs/with-errors">documentos com erros</a>. Editores do site passam por essa lista regularmente para achar e consertar erros. Este artigo detalha os quatro tipos de erros de KumaScript, e alguns passos que você pode fazer para consertá-los.</p> +</div> + +<h2 id="Erro_tipo_DocumentParsingError">Erro tipo <em>DocumentParsingError</em></h2> + +<p><code>DocumentParsingError</code> erros aparecem quando o KumaScript tem problemas para entender alguma coisa no próprio documento. A causa mais comum é um erro de sintaxe em alguma <a href="/en-US/docs/MDN/Contribute/Content/Macros">macro</a>.</p> + +<p>Verifique:</p> + +<dl> + <dt>Uso de chaves sem a intenção de chamar uma macro.</dt> + <dd>Se você pretende escrever \{ num documento sem usar macro, você pode escapar as chaves com uma barra invertida \ da seguinte forma: <code>\\{</code></dd> + <dt>Uso de caractére especial nos parâmetros de uma macro.</dt> + <dd>Se você pretende usar aspas duplas " ou barra invertida \ dentro de algum parâmetro para uma macro, eles podem ser escapados através de uma barra invertida \ da seguinte forma: <code>\\</code> or <code>\"</code></dd> + <dt>Falta de vírgula para separar parâmetros de macro.</dt> + <dd>Parâmetros de macro precisam ser separados por uma vírgula (,) exceto no último parâmetro (ou se for único); por exemplo <code>\{\{anch("top", "Back to top")}}</code>.</dd> + <dt>Tags HTML aparecendo dentro de uma chamada de macro</dt> + <dd>Se você aplicar estilos a uma macro, geralmente não irá funcionar, pois uma tag <code></code></code> pode aparecer dentro do código fonte da macro, causado erros de sintaxe na macro. Verifique a visão de código-fonte para ver o código que foi gerado, e remova qualquer estilo desnecessário.</dd> +</dl> + +<ul> +</ul> + +<h2 id="Erro_tipo_TemplateLoadingError">Erro tipo <em>TemplateLoadingError</em></h2> + +<p><code>TemplateLoadingError</code> erros aparecendo quando um KumaScript tem problemas de encontrar qual <a href="/en-US/docs/MDN/Contribute/Content/Macros">macro</a> incluir numa página.</p> + +<p>Verifique:</p> + +<dl> + <dt>Nomes com erro ortográfico ou macros renomeadas.</dt> + <dd>Você pode ver a lista de macros conhecidas no <a href="https://github.com/mdn/kumascript/tree/master/macros">Repositório do Github</a>.</dd> +</dl> + +<div class="note"> +<p><strong>Dica:</strong> Você pode tornar mais rápido e fácil avançar para uma macro específica adicionando uma <a href="http://kb.mozillazine.org/Using_keyword_searches">busca por palavras-chave</a> no Firefox. Veja {{SectionOnPage("/en-US/docs/MDN/Contribute/Tools/KumaScript", "Using search keywords to open template pages")}} para um guia passo-a-passo de criar uma busca para isso.</p> +</div> + +<h2 id="Erro_tipo_TemplateExecutionError">Erro tipo <em>TemplateExecutionError</em></h2> + +<p><code>TemplateExecutionError</code> erros aparecem quando KumaScript encontra erros na macro. Esses erros só podem ser consertados por usuários administradores e precisam ser reportados como <em>bugs</em>.</p> + +<p>Antes de reportar um erro, verifique se ele ainda não foi consertado. Você pode fazer isso forçando o KumaScript a te dar uma cópia fresca da página segurando <kbd>Shift</kbd> enquanto atualiza a página (<kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>R</kbd> no Windows/Linux, <kbd>Shift</kbd> + <kbd>Cmd</kbd> + <kbd>R</kbd> no Mac).</p> + +<p>Se os erros persistirem, <a href="https://bugzilla.mozilla.org/enter_bug.cgi?product=Mozilla_Developer_Network&component=General#h=detail|bug">reporte um <em>bug</em></a>, incluindo a URL da página e o texto do erro.</p> + +<h2 id="Erro_tipo_Error_Unknown">Erro tipo <em>Error</em> & <em>Unknown</em></h2> + +<p>Este é um tipo de erro que aparece quando o erro não pertence aos outros tipos de erros.</p> + +<p>Verifique se existe alguma solução de contorno ou correção para o problema e reporte <em>bugs</em> persistentes como descrito em <a href="#TemplateExecutionError">TemplateExecutionError</a>.</p> diff --git a/files/pt-br/mdn/tools/page_regeneration/index.html b/files/pt-br/mdn/tools/page_regeneration/index.html new file mode 100644 index 0000000000..16808c9615 --- /dev/null +++ b/files/pt-br/mdn/tools/page_regeneration/index.html @@ -0,0 +1,32 @@ +--- +title: Page regeneration +slug: MDN/Tools/Page_regeneration +tags: + - Ferramentas + - Guia(2) + - MDN Meta + - Page-level +translation_of: MDN/Tools/Page_regeneration +--- +<div>{{MDNSidebar}}</div><p>O site da MDN cacheia as páginas para melhorar a performance. Como resultado, as mudanças que você salva nas páginas podem não aparecer imediatamente. Muitas vezes, mas nem sempre, o banner aparece na página indicando que uma atualização para aquela página está em progresso. Você pode fazer uma "atualização forçada" no seu navegador para recarregar a página do servidor, mas isso pode não ter efeito se a atualização no servidor não estiver completa.</p> + +<p>Algumas páginas (especialmente landing pages) utilizam macros para gerar e atualizar o conteúdo automaticamente. Para landing pages, fazer isso assegura que novos artigos vão automaticamente ser listados na página, sem que um editor tenha que adicioná-los manualmente. Isso é bem conveniente para contribuidores de longas datas e evita que o trabalho dos novatos seja perdido aleatoriamente devido eles não saberem como o inserir o link hierarquicamente para seus artigos.</p> + +<p>Isso também pode ser feito quando a transclusão de conteúdo de uma pátina para outras páginas (usando por exemplo, o macro {{TemplateLink("Page")}}).</p> + +<p>Devido ao cache da MDN ter renderizado o conteúdo para melhorar a performance, mudanças feitas no material fonte (como a saída dos macros ou páginas transcluídas) não são automaticamente refletidas na páginas. Se você espera mudanças frequentes feitas nesses materiais fonte, você pode considerar habilitar a regeneração automática de páginas.</p> + +<p>Para habilitar a regeneração automática de páginas:</p> + +<ol> + <li>Clique no botão <strong>Editar</strong> na página para entrar no modo de edição.</li> + <li>Abaixo do título da página, clique em <strong>Editar o título e propriedades</strong> localizado perto do título da página. Os metadados da página aparecerão.</li> + <li>Selecione um valor para <strong>Tempo máximo de regeneração</strong>. Esse valor determina o intervalo de tempo que as páginas serão refeitas, incluindo a reexecução de seus macros. Tipicamente, nós utilizamos de 4 a 8 horas. Para uma tecnologia em que a documentação está mudando rapidamente, você pode mudar para um número menor.</li> + <li>Salve suas mudanças para a página. É uma boa prática fazer a revisão dos comentários para descrever o que você fez, tipo: "Mudei o tempo máximo de renderização para 4 horas".</li> +</ol> + +<p>Essa página vai ser regerada automaticamente no tempo que você especificou.</p> + +<blockquote> +<p>A opção "Editar títilo e propriedades da página" não está disponível enquanto você cria uma nova página. Você terá que salvar as alterações e reabrir a página para vê-la.</p> +</blockquote> |