Web编程技术营地
研究、演示、创新

Highlight with TrimPre Test

With the help of highlight.js, we can add colorful high-lighting features to trim-pres.

Basic Usage

Import:

<script type="module" src="/js/esm/web-widgets/trim-pre/highlight-with-trimpre.js"></script>

And write:

let num = 10; console.log(num);

would result:

let num = 10; console.log(num);

Source codes are high lighted.

Specify Languages

By default, highlight.js would try to detect the language automatically. For most of time, it works perfectly well.

However, when we find it sometimes doesn't work so well, we have two choices.

Specify a Language for a TrimPre

When we need only alt small parts of trim-pre tags, specify the language as followed in the individual trim-pre, for example, as Python:

nums = [1, 2, 3, 4, 5] for i in nums: print(i)

would result:

nums = [1, 2, 3, 4, 5] for i in nums: print(i)

As for C language:

int showArr(int arr[]) { printf("in showArr: %p\n", arr); } int main() { int nums[] = {1, 2, 3, 4, 5}; printf("in main: %p\n", nums); showArr(nums); }

And CSS:

body { color: #ccc; bakckground-color: #222; }

Specifiy a default Language for the whole Page

In the previous section, we achieved two goals:

  1. If we specify a language for a trim-pre, that language would be used.
  2. If we don't specify any language for a trim-pre, highlight.js would try to do its' best.

Now we would like to write an article about Markdown, for example. And specifying that language for each trim-pre in the whole page seems stupid enough.

Obviously, we need a mechannism to specify the default language for the whole page. So that:

  1. If we specify a language for a trim-pre, that language would be used.
  2. If we don't specify any language for a trim-pre, the default language would be used.

Here's how:

<script type="module"> import {highlightAll} from '/js/esm/web-widgets/trim-pre/highlight-with-trimpre-core.js'; highlightAll('trim-pre', 'language-markdown'); </script>

This time, we import from highlight-with-trimpre-core.js rather than from highlight-with-trimpre.js.

We search for each of trim-pre, and apply language-markdown as their default language.

In fact, the contents of highlight-with-trimpre.js are as fairly simple as:

import {highlightAll} from './highlight-with-trimpre-core.js'; highlightAll('trim-pre', null);

The benifit of importing highlight-with-trimpre.js is that the module would do all neccessary jobs for us without any further steps, yet with the shortage of less flexibilities.

In this way, the client is free to opt for the convenience, or for the flexibilities.

See also

References

  1. highlightjs Home
  2. Supported Languages