Code Blocks and Callouts

    • OUT OF DATE
      +
      This documentation is out of date

      Code Blocks

      Source code examples are entered into AsciiDoc listing blocks. Listing block content is displayed exactly as entered, and any indents and endlines are preserved. If the source style and a language are assigned to the block, the code is syntax highlighted on the site.

      Delimited code block with title
      .Optional title
      [source,java] (1) (2)
      ---- (3)
      KStreamBuilder builder = new KStreamBuilder();
      
      KStream<String, GenericRecord> source = builder
              .stream("streaming-topic-beer-sample");
      ----
      1 Assign the block style source to the first position in the attribute list.
      2 Assign a source language to the second position.
      3 Code the contains blank lines must be entered into a delimited listing block (----).

      Rendered as:

      Optional title
      KStreamBuilder builder = new KStreamBuilder();
      
      KStream<String, GenericRecord> source = builder
              .stream("streaming-topic-beer-sample");

      Commands executed in a CLI are assigned the language console and lines are preceded by the command prompt ($).

      [source,console]
      ----
      $ curl GET -u admin:password http://ip.for.destination.cluster:8091/pools/default/buckets
      ----

      Rendered as:

      $ curl GET -u admin:password http://ip.for.destination.cluster:8091/pools/default/buckets

      Note, using [source,console] ensures that the $ prompt is not copied when the user clicks the clipboard icon that appears upon mouseover above the code block.

      Short code snippets don’t need delimiters as long as they don’t contain blank lines or callouts.

      [source,sql]
      SELECT country FROM `travel-sample` WHERE name = "Excel Airways";

      Rendered as:

      SELECT country FROM `travel-sample` WHERE name = "Excel Airways";

      Code blocks can be grouped in a parent block element.

      ====
      [source,n1ql]
      ----
      SELECT CONTAINS("N1QL is awesome", "N1QL") as n1ql,
             CONTAINS("N1QL is awesome", "SQL") as no_sql;
      ----
      
      [source,json]
      ----
      {
          "results": [
              {
                  "n1ql": true,
                  "no_sql": false
              }
          ]
      }
      ----
      ====

      Rendered as:

      SELECT CONTAINS("N1QL is awesome", "N1QL") as n1ql,
             CONTAINS("N1QL is awesome", "SQL") as no_sql;
      {
          "results": [
              {
                  "n1ql": true,
                  "no_sql": false
              }
          ]
      }

      Callout Numbers

      Callouts add annotations to lines in code blocks. The first callout number must be placed after the final character on a code line. The responding callout is listed below the block and followed by the annotation text. Multiple callout numbers can be used on a single line.

      [source,javascript]
      ----
      function OnUpdate(doc, meta) {
        var strong = 70;
        var stmt =
          SELECT *                  // <1>
          FROM `beer-samples`       // <2>
          WHERE abv > $strong;
        for (var beer of stmt) {    // <3>
          break;                    // <4>
        }
      }
      ----
      <1> N1QL queries are embedded directly.
      <2> Token escaping is standard N1QL style.
      <3> Stream results using 'for' iterator.
      <4> Cancel streaming query by breaking out.

      Rendered as:

      function OnUpdate(doc, meta) {
        var strong = 70;
        var stmt =
          SELECT *                  (1)
          FROM `beer-samples`       (2)
          WHERE abv > $strong;
        for (var beer of stmt) {    (3)
          break;                    (4)
        }
      }
      1 N1QL queries are embedded directly.
      2 Token escaping is standard N1QL style.
      3 Stream results using 'for' iterator.
      4 Cancel streaming query by breaking out.
      To make callouts copy-and-paste friendly, put them behind the line comment syntax of the code snippet’s language. For example, callouts in a YAML example are placed behind the hash symbol (#).

      The callout list does not have to follow immediately after the code block containing the callouts. For example, you can include an introductory sentence or paragraph between the code block and the callout list.

      Instead of marking up each callout with its own number, such as <1>, <2>, <3>, you can use <.> for each callout. When you use this method, the callouts are numbered automatically.

      Inserting Examples with the Include Directive

      The include directive inserts an entire file or tagged region from a file stored in the examples directory of a module into a code block. Just specify the resource ID of the example file in the directive.

      .Query result
      [source,json]
      ----
      include::example$contact.json[]
      ----

      You will find most of the SDK code samples included in $examples directories alongside the pages parent to the .adoc file that is calling them. Else you will find thim in a special devguide/examples module in each SDK docs repo. Using include:: adds a Git hub link on mouseover, which leads to the code file on the repo.

      For a tagged region of a source file, set the tags around the code sample using the comment character appropriate to the source language, such as // or #:

      [source,ruby]
      ----
      # tag::read-only[]
      options = Cluster::QueryOptions.new
      options.readonly = true
      cluster.query(
          'SELECT COUNT(*) AS airport_count FROM `travel-sample` WHERE type = "airport"',
          options)
      # end::read-only[]
      ----

      And add the appropriate [tag=] to the include::.

      .Read-only Query
      [source,json]
      ----
      include::example$query.rb[tag=read-only]
      ----

      Note that we aim to keep all code files in the examples directory runnable — or at least compilable — so if you are adding a snippet of code to an existing file, please test it.

      Try It Now

      The Couchbase documentation integrates with https://couchbase.live to offer an interactive code console called “Try It Now”. This feature can be enabled per code block.

      To add a “Try It Now” mode to a code block, you need two things:

      1. A standalone code sample that can be executing on couchbase.live

      2. The try-it role on the block to indicate that the code is compatible with couchbase.live

      When the “Try It Now” mode is enabled, a Run Code button will appear in the toolbar above the code block. When the user clicks on this button, it will split the page into two panes, with the documentation on the left and the output console on the right. It will also make the code block editable. The reader can either reexecute the code using the refresh button above the output console or by clicking the Run Code button again. Clicking the Run Code button submits the updated code, whereas the refresh button reexecutes the previous code.

      Here’s an example of a code block with the “Try It Now” mode enabled:

      [source.try-it,js]
      ----
      const couchbase = require('couchbase')
      
      const cluster = new couchbase.Cluster('couchbase://127.0.0.1', {
        username: 'username', password: 'password'
      })
      
      const bucket = cluster.bucket('travel-sample')
      const collection = bucket.defaultCollection()
      
      const getDocument = async (key) => {
        try {
          const result = await collection.get(key)
          console.log(result)
        } catch (err) {
          console.error(err)
        }
      }
      
      getDocument('airline_10')
        .then(() => process.exit(0))
      ----

      Here’s how it appears when rendered:

      const couchbase = require('couchbase')
      
      const cluster = new couchbase.Cluster('couchbase://127.0.0.1', {
        username: 'username', password: 'password'
      })
      
      const bucket = cluster.bucket('travel-sample')
      const collection = bucket.defaultCollection()
      
      const getDocument = async (key) => {
        try {
          const result = await collection.get(key)
          console.log(result)
        } catch (err) {
          console.error(err)
        }
      }
      
      getDocument('airline_10').then(() => process.exit(0))

      The code sample has to be compatible with couchbase.live. The one exception is for Java. You can use a public class with any class name and the supporting script will rewrite the class name as Program.

      Additional Resources