User Tools

Site Tools


ru:how_to:editor_configuration_custom_files

This is an old revision of the document!



Файлы конфигурации редактора

Редактор CKEditor, включаемый в состав GetSimple, поставляется с файлом конфигурации по умолчанию и файлом стилей по умолчанию. У пользователей есть возможность создавать собственный конфигурационный файл, который не будет переписываться при очередном обновлении системы, для определения настроек редактора, которые отсутствуют в его усеченной версии для GS.

Стандартный файл конфигурации

Стандартный файл конфигурации редактора, идущий с пакетом GetSimple, располагается в папке Корневой_каталог_системы/admin/template/js/ckeditor и практически пуст:

Он содержит всего 2 опции:

CKEDITOR.editorConfig = function( config )
{
	// Определяйте изменения конфигурации по умолчанию здесь. Например:
	config.removePlugins = 'elementspath,resize' ; // не показывать путь к элементу, запретить изменение размера
	config.toolbarCanCollapse = false; //скрыть кнопку сворачивания панели инструментов
};

Разумеется, дополнительные параметры конфигурации редактора можно указывать и в этом файле, но он будет переписываться с каждым обновлением системы. Поэтому лучшим решением будет создание пользовательского конфигурационного файла и хранение его в безопасном месте.

Пользовательский файл конфигурации

Преимуществом редактора CKEditor является возможность определения собственного конфигурационного файла или файла пользовательских настроек. Казалось бы, зачем вообще нужен такой файл? Вы уже убедились, что значительное количество параметров CKEditor определяется в файле настроек системы GetSimple gsconfig.php.

Для создания собственных настроек есть несколько причин:

  • Вам необходимо добавить большое количество опций и вам по какой-то причине удобнее сделать это в файле config.js, а не в gsconfig.php
  • Вы хотите не только определить настройки редактора, но и , например, управлять поведением диалоговых окон
  • Вы хотите изменить автоматическое форматирование текста редактором по умолчанию

Процесс создания файла пользовательской конфигурации достаточно прост. Файл config.js представляет собой обычный javascript-файл.

  • Возьмите файл config.js, который поставляется с GetSimple, переименуйте его и сохраните в папке data или theme.
  • Отредактируйте его и загрузите на сервер в соответствующую папку, проверьте права доступа (файл должен быть доступен на чтение);
  • Пропишите наименование и путь к вашему файлу конфигурации редактора в файле gsconfig.php в параметре GSEDITOROPTIONS.

Пример:

define('GSEDITOROPTIONS', "entities : false,customConfig : '../../../../theme/папка_вашей_темы/yourconfigfile.js',skin: 'v2'
");

Эта инструкция определяет, что пользовательский файл конфигурации редактора с именем yourconfigfile.js расположен в папке с вашей активной темой папка_вашей_темы.

Еще пример:

define('GSEDITOROPTIONS', "entities : false,customConfig : '../../../../data/editorconfig/yourconfigfile.js',skin: 'v2'
");

Для данного случая необходимо создать папку editorconfig в папке data и загрузить файл конфигурации в эту папку. Проверьте, не запрещен ли доступ к js-файлам в папке data в соответствующем .htaccess файле.

Пример файла пользовательской конфигурации CKEditor:

/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
	// Определяйте изменения настроек редактора по умолчанию здесь. Например:
	config.toolbarCanCollapse = true,
	config.enterMode = CKEDITOR.ENTER_P,
	config.shiftEnterMode = CKEDITOR.ENTER_BR,
	config.colorButton_enableMore = true,
  	config.bodyId = 'content',
	config.entities = false,
	config.forceSimpleAmpersand = false,
	config.fontSize_defaultLabel = '12px',
	config.font_defaultLabel = 'Arial',
	config.emailProtection = 'encode',
	config.contentsLangDirection = 'ltr',
	config.language = 'en',
	config.contentsLanguage = 'en',
	config.toolbarLocation = 'top',
	config.browserContextMenuOnCtrl = false,
	config.image_previewText = CKEDITOR.tools.repeat('Get-Simple - the best CMS for your purposes. Install it, test it, enjoy it. Free, OpenSource and userfriendly', 50 )
		};
// из  http://help.pixelandtonic.com/brandonkelly/topics/how_do_i_set_output_formatting_writer_rules?from_gsfn=true 
CKEDITOR.on( 'instanceReady', function( ev ) {

var blockTags = ['div','h1','h2','h3','h4','h5','h6','p','pre','ul','li'];
var rules = {
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : true
};

for (var i=0; i<blockTags.length; i++) {
ev.editor.dataProcessor.writer.setRules( blockTags[i], rules );
}

});

// из  http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Dialog_Customization

CKEDITOR.on( 'dialogDefinition', function( ev )
	{
		// Берем наименование диалога и его определение из данных события.
		var dialogName = ev.data.name;
		var dialogDefinition = ev.data.definition;
 
		// Проверяем, тот ли это диалог, который нас интересует.
		 
		if ( dialogName == 'link' )
		{
			/* Включаем эту часть только если вы не убираете вкладку 'target' в предыдущем блоке.  */
 			FCKConfig.DefaultLinkTarget = '_blank'
			// Получаем ссылку на вкладку "Target".
			var targetTab = dialogDefinition.getContents( 'target' );
			var targetField = targetTab.get( 'linkTargetType' );
			targetField[ 'default' ] = '';
			linkField[ 'default' ] = 'URL';

		} //  окончание для dialogDefinition
 
		if ( dialogName == 'image' )
		{
		 dialogDefinition.removeContents( 'advanced' );
		dialogDefinition.removeContents( 'Link' );
		}
 
		if ( dialogName == 'flash' )
		{
					dialogDefinition.removeContents( 'advanced' );
		}
 
	});

Standard Stylesheet

ckeditorstylecombo.jpgVery often, users do not want to use the styles which come by default in the style-combo-box. They want to have another choice.

By default, the stylesheet which defines the contents of the dropdown-list, is called default.js and is located in the folder yourGetSimpleRootDirectory/admin/template/js/ckeditor/plugins/styles/styles/default.js

You can edit this file, but as it is a compressed file, this will be no real pleasure, and, what is more important, this file will be overwritten with every upgrade.

So it is much more handy to define your own stylesheet-configuration and store it at a save location.

Custom Stylesheet

Here are the steps to install your custom stylesheet in short.

  1. get an umcompressed copy of the default stylesheet here from CKEditor's homepage
  2. name this file whatever and upload it to a secure place, for example into the data- or the theme-folder
  3. now edit the gsconfig.php and re-upload it to your server.

Now with more details:

  • you need the advanced editor-toolbar to use the styles-combo-box. If you have not done yet, activate that toolbar.
    define('GSEDITORTOOL', 'advanced');
  • add the stylesheet-definition to the Editor-Options:
define('GSEDITOROPTIONS',"stylesSet: 'default:http://www.yourdomain.de/getsimple-root/themes/ckeditorstyles.js'");

Now, what to edit in this file?

The CKEditor-Styleset contains definitions for the following styles:

  • Block-Styles (already defined, but can be overwritten)
  • Inline-Styles
  • Object-Styles

Define the category for the element you want to add here and edit the file at the relevant place. The syntax:

	{ name : 'Computer Code', element : 'code' },

or

{ name : 'Marker: Yellow', element : 'span', styles : { 'background-color' : 'Yellow' } },

or even

{
		name : 'Image on Left',
		element : 'img',
		attributes :
		{
			'style' : 'padding: 5px; margin-right: 5px',
			'border' : '2',
			'align' : 'left'
		}
	},

One definition must contain at least 2 parameters: name and element. You are free to set the name to whatever you want. element stands for the HTML-element which will be added to the HTML-Output, when you mark some text in the editor and activate this style.

So with these definitions you can add often used formats with an explanatory name to the dropdown-list (and you can delete those which only annoy and are never used).

If you want to add HTML-attributes to the elements in the style-combo, you need the third parameter attributs e.g.

{ name : 'Tablecell top', element : 'td', attributes : { 'valign' : 'top' } },

for CSS-styles, you use the parameter styles. E.g.

{ name : 'Red table', element : 'table', styles : { 'background-color':'red' } },


HTML or XHTML output ?

CKEditor by default wraps the content using XHTML tags (every tag has to be enclosed), and in such way formats it.
To get rid of / in closing tags (to achieve for example <br> [HTML] instead of <br /> [XHTML]) upon saving page ,
you need to edit CKE's config.js file located in admin/template/js/ckeditor/ , and add below code:

CKEDITOR.on( 'instanceReady', function( ev )
    {
        ev.editor.dataProcessor.writer.selfClosingEnd = '>';
    });
ru/how_to/editor_configuration_custom_files.1382000868.txt.gz · Last modified: 2013/10/17 09:07 by Arkady