Evgenii Legotckoi
Evgenii LegotckoiSept. 16, 2016, 3:25 p.m.

Django - Tutorial 002. Syntax highlighting of code on site

The biggest problem when you start writing a site from scratch on the Django was code syntax highlighting. Okay, I was on Wordpress the plugin that works with the task, though a bit loaded site as highlighting was organized on the server side. But in the case with the new site had already been thinking about it.


First choice was the issue of where it will be organized syntax highlighting:

  • On the server side
  • Or on the client side

Searching the information I found out that for the organization of the syntax in the ready-made solutions server side is not so much, for example Geshi, yes, and perhaps all, what works in Python. And he can load the server if there are problems in caching.

But with syntax highlighting on the client side it has become more interesting. Here for example, and Hightlight.js and SyntaxHighlighter , and lightweight script Google's good Corporation, Javascript Code Prettifier , on his choice, and fell. Especially because it is used in such a well-known resource as Stack Overflow .

Implementing

Perhaps the biggest advantage of this script is its high speed and easy implementing and configuration.

Connect this script can be a single line, but it must be connected to the bottom of the page that triggered the code syntax highlighting.

<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>

Using

To use this functionality you need to wrap the script code in the tag illuminated, indicating the class prettyprint

<pre class="prettyprint">...</pre>

or
<code class="prettyprint">...</code>

<pre class="prettyprint">
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Hello World!" << endl;
    return 0;
}
</pre>

Support of languages

The script supports multiple languages, which are indicated by a class lang- * with the appropriate extension for a specific language.

<pre class="prettyprint lang-html">
  The lang-* class specifies the language file extensions.
  File extensions supported by default include
    "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html",
    "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh",
    "xhtml", "xml", "xsl".
</pre>

Line Numbering

Also, the script supports line numbering. To do this, you must specify linenums class. If it is necessary to clarify that the code begins with a specific string, then a colon must specify that line number, ie linenums:18 .

Default numbering goes every five lines, that is, 5, 10, 15, 20, etc. If you want to number every line, then you need to add additional styles for this script. They can be added to the file of your website style.

<style>
li.L0, li.L1, li.L2, li.L3,
li.L5, li.L6, li.L7, li.L8
{ list-style-type: decimal !important }
</style>

The result will be as follows:

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Hello World!" << endl;
    return 0;
}

For Django I recommend VDS-server of Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 11:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks