Install the Discourse Theme CLI console app to help you build themes

The discourse Discourse Theme CLI is a ruby gem that allows you to use your editor of choice when developing Discourse themes and theme components. As you save files the CLI will update the remote theme or component and changes to it will appear live!

Installing

To play with it, make sure you have Ruby 2.5 or up installed.

If you are on Windows, you have 2 options:

Option 1: Windows Subsystem for Linux.

Windows 10 has access to a full Linux environment, you can use it to install ruby simply with sudo apt-get install ruby, this will give you Ruby 2.3.

Options 2: Older Windows

Older versions of Windows have no access to WSL, you can easily install Ruby with Ruby Installer, go for the recommended version and default settings for the install.

Mac OS version 10.13.3 ship with Ruby 2.3 out of the box, nothing special is needed. If you are running an earlier version of Mac OS consider using rvm, rbenv or homebrew to install a recent ruby.


Once Ruby 2.2 or later is running, open a terminal or command shell and run:

gem install discourse_theme

Once installed, to learn more about it:

discourse_theme

Upgrading

gem update discourse_theme

Features

The CLI provides 3 main functions:

discourse_theme new

You can use it to quickly create a new theme with discourse_theme new YOUR_DIR_NAME

discourse_theme watch

You can use it to monitor a theme and synchronize with a discourse site (with live refresh) using discourse_theme watch YOUR_DIR_NAME

What this means is that you can use your own editor to edit you theme and site will magically :unicorn: update with the changes!

discourse_theme download

You can download an existing theme from Discourse using discourse_theme download YOUR_DIR_NAME. You will then be given the option to start “watching” straight away!

Credentials

You will need to generate an API Key. Go to the admin area and generate a key there.

  • :exclamation: Select a “User Level” of Single User when generating the key, not All Users.
  • :exclamation: Make sure to check Global Key or you will receive 403 forbidden errors.

Credentials are (optionally) stored at ~/.discourse_theme. API keys are stored per-site, and the URL/theme_id for each directory is also tracked. If you ever need to change your settings, just add --reset to any command and you will be prompted for all values again.

Testimonials

“This tool is truly a GEM!” @awole20
“This is very very good.” @awesomerobot
“It’s working :slight_smile: And it’s pretty dosh garn cool. Nice!” @angus
“OMG. It’s unbelievable.” @pfaffman


This document is version controlled - suggest changes on github.

79 лайков
Theme Creator, create and show themes without installing Discourse!
CSS Theme Contest (with Prizes!)
Customizing handlebars templates
Setting up a solid workflow for custom theme development
Theme Developer Quick Reference Guide
Structure of themes and theme components
Automating Discourse Plugin Setup with `create-discourse-plugin` gem
When exporting a theme, I get a broken archive
Install Discourse for development using Docker
Developing Plugins Faster by separating the frontend into a theme component
Feedback on "on-discourse" javascript for setting up custom JS for each page?
Add settings to your Discourse theme
Get started with Theme Creator and the Theme CLI
Designer's Guide to getting started with themes in Discourse
Split up theme Javascript into multiple files
Updated Custom Header Icon: Post Data via URL
Theme Developer Tutorial: 2. Creating a remote theme
Developing Discourse Themes & Theme Components
Hiding GUI elements for new users (less overwhelming)
Add custom content that only appears on your homepage
Custom CSS/HTML
[Zotero extension +] Firefox v116 on macOS broken Discourse?
If you want to edit this theme, you must submit a change on its repository
How "difficult" is modifying/extending Discourse for a backend dev
Exporting a Theme from Staging and Importing it to the Production portal
Using Plugin Outlet Connectors from a Theme or Plugin
Downloaded component installs fine, but does not once changed/re-zipped
What are the benefits of a dev environment?
3.2.0.beta2-dev (7019dbcfe1) does not load CSS from common.scss anymore
End-to-end system testing for themes and theme components
Different CSS changes for different color schemes
Need help integrating code wrote on Edittext to the Discourse
Remote themes not in database
How to add a custom button in user profile card?
How to easily edit my site remotely?
When to use a plugin vs theme component?
Discourse core is switching to pnpm for JS package management
Using the new custom-homepage feature
Focus the editor when title is pre-filled
Cannot put the template in the desired outlet
Is this the correct way to create a theme component?
Split up theme Javascript into multiple files
Canvas Theme Template
Getting error while uploading theme
Need help integrating code wrote on Edittext to the Discourse
Import site theme via console
How are theme setting fields created?
Customisability in discourse?
Edit CSS/HTML editor cursor offset makes it unusable due to CSS font override
Discourse Theme CLI is the bomb
Discourse 2.0.0.beta5 Release Notes
How difficult would it be to make the Discourse UI more like Flarum?
Discourse-webpack: A boilerplate for developing JS-heavy Discourse components
Import Error: about.json does not exist, or is invalid
How to Add Unique HTML Content Below Topic Body in discourse forum for Specific Topics
Reuse Discourse Hamburger Functionality
Themes - Add a description field
Create and share a font theme component
Customisability in discourse?
How to create a theme (if I am a pure end user)
Linting configuration
Linting configuration
Is it possible to use a local plugin directory with a docker install?
How to overrule a color variable for one theme only?
Can't customize text on custom button in template override using UI
Is it possible to use theme component from local folder (as plugin) - for local development?
Restrict editing of remote themes

Загрузки через Администратор >> Настроить >> Темы исчезают после сохранения просматриваемой темы.

Как включить изображения в тему, чтобы они не удалялись после сохранения?

2 лайка

Привет, добро пожаловать!

Вам нужно включить ресурсы напрямую в компонент вашей темы.

В корневой директории создайте папку assets.
Затем объявите их в файле about.json:

"assets": {
  "<your_identifier>": "assets/<your_asset_filename>",
}

Пример можно посмотреть здесь: GitHub - MeghnaAJ/discourse-christmas-decorations · GitHub.

3 лайка

Краткое уведомление для разработчиков, использующих этот инструмент для генерации компонентов темы:
Рекомендуем обновить его! :+1:

Недавний PR сделал репозиторий discourse-theme-skeleton шаблоном по умолчанию. Это обеспечит вам получение последних файлов конфигурации!

9 лайков

Спасибо!

Было бы здорово добавить раздел «Обновления» к теме…

Это команда --reset или обновление rubygem?

4 лайка

Отличная идея! Я добавил раздел «Обновление» в первое сообщение

gem update discourse_theme
5 лайков

Для установки гема в WSL мне пришлось выполнить обе команды: sudo apt-get install ruby и sudo apt-get install ruby-dev. Возможно, стоит добавить это в инструкции по установке.

Если вы не установите ruby-dev, возникнет ли ошибка? Установка ruby-dev не должна быть обязательной, так как самого ruby достаточно.

4 лайка

Я почти уверен, что получил ошибку, в которой говорилось установить ruby-dev, иначе я бы не знал о существовании этого пакета. Но я не могу воспроизвести это, пытаясь переустановить. Возможно, в первый раз я что-то сделал не так.

2 лайка

Хм, это действительно странно. Дайте знать, если вам удастся воспроизвести проблему снова.

2 лайка

Вчера я обновил свой сервер до версии 3.5.0.beta9-dev, и с тех пор у меня не работают live reloads с темой Discourse gem. Версия gem — 2.1.6.

Я не вижу никаких ошибок и подобных проблем, поэтому сначала хотел спросить, сталкивался ли кто-то ещё с такой же проблемой?

2 лайка

Живая перезагрузка таблиц стилей отключена для продакшн-инстансов, так как она вызывала проблемы при обновлении тем и/или ядра Discourse.

В основе проблемы: изменения в таблицах стилей часто связаны с изменениями в JS/HTML, поэтому живая загрузка только для таблиц стилей рискованна. В результате пользователи получают «новые» таблицы стилей, применяемые к «старому» HTML, что может привести к очень странным ситуациям.

Живая загрузка по-прежнему включена для инстансов Discourse в режиме разработки. В идеале используйте её именно для разработки, а не для продакшн-сайта. Помимо перезагрузки таблиц стилей, режим разработки Ember предоставляет гораздо более дружелюбные сообщения об ошибках по сравнению с режимом продакшн.

3 лайка

Это серьёзное изменение. Меня удивляет, что не было объявления. Я занимался разработкой тем в основном только на продакшн-сайтах.

Было бы неплохо добавить настройку сайта, чтобы вернуть старое поведение.

6 лайков

Согласен, это меня удивило, и я не смог найти эту текущую ветку, несмотря на поиск, или, возможно, я увидел более старую дату создания темы и проигнорировал её.

1 лайк

Сообщение было перенесено в новую тему: Как восстановить предыдущую тему