DefaultOption

View as Markdown

DefaultOption

DefaultOption is the implementation of the Option interface that the SDK provides. It writes the marks, nodes and embedded items of a JSON Rich Text Editor (JSON RTE) field as HTML tags. Use this class to

Create one with new DefaultOption(). The class has no constructor arguments and no setters.

renderMark

renderMark wraps the text of a JSON Rich Text Editor text node in the HTML tag for one formatting mark.

NameTypeDescription
markType (required)MarkType

Formatting mark to apply, such as BOLD.

Default: Not applicable
text (required)String

Text to wrap, which already carries earlier marks.

Default: Not applicable

Returns: String. The text wrapped in the mark's HTML tag.

Validation

  • There is no client-side validation.
  • renderMark throws NullPointerException when markType is null. NodeToHTML textNodeToHTML, the method that calls it, always passes a mark and a non-null text.

Behavior

  • Client-side only. renderMark builds a string and makes no request.
  • The table below lists the HTML that renderMark writes for each mark:
MarkHTML
SUPERSCRIPT<sup>text</sup>
SUBSCRIPT<sub>text</sub>
INLINECODE<span>text</span>
STRIKETHROUGH<strike>text</strike>
UNDERLINE<u>text</u>
ITALIC<em>text</em>
BOLD<strong>text</strong>
BREAK<br /> followed by the text minus its line breaks
  • Inline code becomes a <span> tag, not a <code> tag.
  • MarkType is package-private, so your code cannot call renderMark directly. Pass the DefaultOption to textNodeToHTML or SDKUtil.jsonToHTML, which call renderMark once for each mark on a text node. See Option renderMark for the order of the calls.

Example

Basic usage: see the tag for each mark

import android.util.Log;

import com.contentstack.sdk.DefaultOption;
import com.contentstack.sdk.NodeToHTML;

import org.json.JSONException;
import org.json.JSONObject;

try {
    DefaultOption option = new DefaultOption();
    JSONObject squared = new JSONObject().put("text", "2").put("superscript", true);
    JSONObject command = new JSONObject().put("text", "gradle build").put("inlineCode", true);
    JSONObject oldPrice = new JSONObject().put("text", "$40").put("strikethrough", true);
    JSONObject nextLine = new JSONObject().put("text", "Next line").put("break", true);

    Log.d("Contentstack", NodeToHTML.textNodeToHTML(squared, option));  // <sup>2</sup>
    Log.d("Contentstack", NodeToHTML.textNodeToHTML(command, option));  // <span>gradle build</span>
    Log.d("Contentstack", NodeToHTML.textNodeToHTML(oldPrice, option)); // <strike>$40</strike>
    Log.d("Contentstack", NodeToHTML.textNodeToHTML(nextLine, option)); // <br />Next line
} catch (JSONException e) {
    Log.e("Contentstack", e.getMessage());
}

renderNode

renderNode writes one block or inline node of a JSON Rich Text Editor field, and its children, as an HTML tag.

NameTypeDescription
nodeType (required)String

Type of the node, such as p or h2.

Default: Not applicable
nodeObject (required)JSONObject

The node, with its attrs and children.

Default: Not applicable
callback (required)NodeCallback

Renders the node's children as HTML.

Default: Not applicable

Returns: String. The HTML for the node and its children.

Validation

  • There is no client-side validation.
  • renderNode throws NullPointerException in three cases:
    • An a, img or embed node has no attrs object.
    • The node has no children array.
    • A style attribute holds a value that is not a JSON object.
  • The exception passes up through SDKUtil.jsonToHTML to your code.

Behavior

  • Client-side only. renderNode builds a string and makes no request.
  • renderNode writes each key of the node's attrs as an HTML attribute (key="value"), except href, asset-link, src and url. A style attribute that holds a JSON object becomes CSS declarations in the form property: value; .
  • The table below lists the HTML that renderNode writes for each node type:
Node typeHTML
p, h1 to h6, ol, ul, li, table, thead, tbody, tfoot, tr, th, td, blockquote, code, fragmentThe tag of the same name around the children, for example <p>children</p>
a<a href="{href}">children</a>, with the URL from the href attribute, or from url when href is empty
img<img src="{url}" /> followed by the children, with the URL from asset-link, then url, then src. When attrs also has a link and the URL came from asset-link or url, an <a href="{link}"> tag wraps the image and the children
embed<iframe src="{url}" followed by the children and </iframe>, with the URL from src, or from url when src is empty
hr<hr /> without children
referenceAn empty string
Any other typeThe children without a tag
  • renderNode HTML-encodes the URL in each href and src with TextUtils.htmlEncode. It writes other attribute values as it receives them.
  • Known issue: renderNode writes an embed node as <iframe src="..." followed by </iframe>, with no > to close the opening tag. Replace "</iframe> with "></iframe> in the HTML before you display it, as the second example below shows.
  • NodeCallback is package-private, so your code cannot call renderNode directly. Pass the DefaultOption to SDKUtil.jsonToHTML, which calls renderNode for each node. See Option renderNode for when jsonToHTML calls it.

Example

Basic usage: render a heading, a paragraph with a link, and a list

import android.util.Log;

import com.contentstack.sdk.DefaultOption;
import com.contentstack.sdk.SDKUtil;

import org.json.JSONException;
import org.json.JSONObject;

try {
    // An entry with one JSON RTE field, "body"
    JSONObject entryJson = new JSONObject("{\"body\":{\"type\":\"doc\",\"children\":["
            + "{\"type\":\"h2\",\"attrs\":{},\"children\":[{\"text\":\"Features\"}]},"
            + "{\"type\":\"p\",\"attrs\":{},\"children\":[{\"text\":\"Read the \"},"
            + "{\"type\":\"a\",\"attrs\":{\"url\":\"https://www.example.com/guide\"},\"children\":[{\"text\":\"guide\"}]},"
            + "{\"text\":\".\"}]},"
            + "{\"type\":\"ul\",\"attrs\":{},\"children\":["
            + "{\"type\":\"li\",\"attrs\":{},\"children\":[{\"text\":\"Fast\"}]},"
            + "{\"type\":\"li\",\"attrs\":{},\"children\":[{\"text\":\"Light\"}]}]}]}}");
    SDKUtil.jsonToHTML(entryJson, new String[]{"body"}, new DefaultOption());
    Log.d("Contentstack", entryJson.getString("body"));
    // <h2>Features</h2><p>Read the <a href="https://www.example.com/guide">guide</a>.</p><ul><li>Fast</li><li>Light</li></ul>
} catch (JSONException e) {
    Log.e("Contentstack", e.getMessage());
}

Edge case: close the iframe tag of an embed node

import android.util.Log;

import com.contentstack.sdk.DefaultOption;
import com.contentstack.sdk.SDKUtil;

import org.json.JSONException;
import org.json.JSONObject;

try {
    JSONObject entryJson = new JSONObject("{\"body\":{\"type\":\"doc\",\"children\":["
            + "{\"type\":\"embed\",\"attrs\":{\"url\":\"https://www.example.com/video\"},\"children\":[{\"text\":\"\"}]}]}}");
    SDKUtil.jsonToHTML(entryJson, new String[]{"body"}, new DefaultOption());
    String html = entryJson.getString("body"); // <iframe src="https://www.example.com/video"</iframe>
    html = html.replace("\"</iframe>", "\"></iframe>");
    Log.d("Contentstack", html); // <iframe src="https://www.example.com/video"></iframe>
} catch (JSONException e) {
    Log.e("Contentstack", e.getMessage());
}

renderOptions

renderOptions writes an entry or asset embedded in a JSON Rich Text Editor field as HTML, in the form its display style sets.

NameTypeDescription
embeddedObject (required)JSONObject

JSON of the embedded entry or asset.

Default: Not applicable
metadata (required)Metadata

Details of the reference, including its display style.

Default: Not applicable

Returns: String. The HTML for the embedded item.

Validation

  • There is no client-side validation.
  • renderOptions throws NullPointerException when metadata is null, and when embeddedObject is null for the BLOCK, LINK or DISPLAY style.

Behavior

  • Client-side only. renderOptions reads the JSON you pass and makes no request.
  • renderOptions reads only the display style from metadata, through Metadata getStyleType. Every other value comes from embeddedObject.
  • In the table below, {name} is the item's title when it is present and not empty, otherwise its uid. {alt} is the title, otherwise the filename, otherwise the uid.
Display styleHTML
BLOCK<div><p>{name}</p><div><p>Content type: <span>{_content_type_uid}</span></p></div>
INLINE<span>{name}</span>
LINK<a href="{url}">{name}</a>
DISPLAY<img src="{url}" alt="{alt}" />
DOWNLOADAn empty string
  • The BLOCK output does not close its outer <div> tag.
  • renderOptions writes the title, UID, URL and content type UID as it receives them, without escaping.
  • SDKUtil.jsonToHTML never calls renderOptions in this version of the SDK, so your code calls it to show an embedded entry. See the Known issue under Embedded entries and assets on the Option class page.

Example

Basic usage: render the embedded items of a fetched entry

import android.util.Log;

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.DefaultOption;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.Metadata;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.jar.Attributes;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");
    // Asks the API to add the embedded entries and assets under _embedded_items
    entry.includeEmbeddedItems();
    entry.fetch(new EntryResultCallBack() {
        @Override
        public void onCompletion(ResponseType responseType, Error error) {
            if (error == null) {
                JSONObject embeddedItems = entry.getJSONObject("_embedded_items");
                if (embeddedItems == null) {
                    return;
                }
                DefaultOption option = new DefaultOption();
                Iterator<String> keys = embeddedItems.keys();
                while (keys.hasNext()) {
                    JSONArray items = embeddedItems.optJSONArray(keys.next());
                    if (items == null) {
                        continue;
                    }
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject item = items.optJSONObject(i);
                        if (item == null) {
                            continue;
                        }
                        Metadata metadata = new Metadata(item.optString("title"), "entry",
                                item.optString("uid"), item.optString("_content_type_uid"),
                                "BLOCK", "", new Attributes());
                        Log.d("Contentstack", option.renderOptions(item, metadata));
                    }
                }
            } else {
                // The API rejected the request or the network failed
                Log.e("Contentstack", "Request failed: " + error.getStatusCode() + " "
                        + error.getErrorCode() + " " + error.getErrorMessage());
            }
        }
    });
} catch (Exception e) {
    // Contentstack.stack throws when a credential is null
    Log.e("Contentstack", "Setup failed: " + e.getMessage());
}

All parameters: compare the HTML for three display styles

import android.util.Log;

import com.contentstack.sdk.DefaultOption;
import com.contentstack.sdk.Metadata;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.jar.Attributes;

try {
    DefaultOption option = new DefaultOption();
    JSONObject article = new JSONObject()
            .put("uid", "<ENTRY_UID>")
            .put("title", "Spring launch")
            .put("url", "/blog/spring-launch")
            .put("_content_type_uid", "<CONTENT_TYPE_UID>");
    String[] styles = {"BLOCK", "INLINE", "LINK"};
    for (String style : styles) {
        Metadata metadata = new Metadata("Spring launch", "entry", "<ENTRY_UID>",
                "<CONTENT_TYPE_UID>", style, "", new Attributes());
        Log.d("Contentstack", style + ": " + option.renderOptions(article, metadata));
    }
    // BLOCK: <div><p>Spring launch</p><div><p>Content type: <span><CONTENT_TYPE_UID></span></p></div>
    // INLINE: <span>Spring launch</span>
    // LINK: <a href="/blog/spring-launch">Spring launch</a>
} catch (JSONException e) {
    Log.e("Contentstack", e.getMessage());
}