Difference between revisions of "Project Templates/ru"

From Lazarus wiki
Jump to navigationJump to search
Line 5: Line 5:
 
Вы можете приспособиться при создании новых проектов. Среда IDE позволяет регистрировать собственные типы проектов с помощью пакетов designtime. Пакет '''projtemplates''' ( он предварительно установлен в обычных бинарных пакетах Lazarus) позволяет просто использовать существующие проекты в качестве шаблонов.
 
Вы можете приспособиться при создании новых проектов. Среда IDE позволяет регистрировать собственные типы проектов с помощью пакетов designtime. Пакет '''projtemplates''' ( он предварительно установлен в обычных бинарных пакетах Lazarus) позволяет просто использовать существующие проекты в качестве шаблонов.
  
=Package projtemplates=
+
=Пакет projtemplates=
  
This package implements project templates and comes with the lazarus sources (components/projecttemplates/projtemplates.lpk).
+
Этот пакет реализует шаблоны проектов и поставляется с исходными кодами lazarus (components/projecttemplates/projtemplates.lpk).
  
The package comes preinstalled with the binary packages of Lazarus (e.g. the windows installer). This package adds a category to the '''File-New''' dialog: '''Template projects'''
+
Пакет поставляется с предустановленными бинарными пакетами Lazarus (например, установщик Windows). Этот пакет добавляет категорию в диалог '''File-New''': '''Template projects'''
  
It also adds a '''New project from Template''' menu item to the '''File''' menu, as
+
Он также добавляет пункт меню '''New project from Template''' в меню '''File''', а также меню '''project template options''' в разделе '''Tools''' [общего] меню. Этот пункт меню отображается только в том случае, если каталог шаблонов (см. следующий абзац) существует и содержит хотя бы один подкаталог шаблонов.
well as a '''project template options''' menu under the '''Tools''' menu.
 
This menu item is visible only if the templates directory (see next paragraph)
 
exists and contains at least one template subdirectory.
 
  
In the ''Project template options'', a directory can be selected. This directory
+
В [разделе] ''Project template options'' можно выбрать каталог. Этот каталог должен содержать подкаталог для каждого шаблона. Каждый каталог шаблонов содержит шаблон для проекта: набор файлов, которые будут скопированы и использованы в качестве нового проекта.
should contain a subdirectory per template. Each template directory contains
 
a template for a project: A collection of files which will be copied and
 
used as a new project.
 
  
During the copy, the package will scan the file/directory names and the
+
Во время копирования пакет будет сканировать имена файлов/каталогов и содержимое файлов для подстановки переменных: '''__VARNAME__''' будет заменено значением переменной VARNAME
contents of the files for variable substitution: '''__VARNAME__''' will be
 
replaced by the value of a variable VARNAME
 
  
By default, the engine knows 2 variables:
+
По умолчанию движок знает о 2 переменных:
*ProjDir: The directory where the new project will be created.
+
*ProjDir: Каталог, в котором будет создан новый проект.
*ProjName: The name of the project.
+
*ProjName: Название проекта.
  
Additional variables must be defined in a file called '''project.ini''' in the
+
Дополнительные переменные должны быть определены в файле с именем '''project.ini''' в каталоге проекта. Это - файл в формате Windows INI.
directory of the project. This is a file in Windows INI format.
 
  
The section ''[Variables]'' will be scanned for variable names:
+
Раздел ''[Variables]'' будет сканироваться на предмет имен переменных:
 
  [Variables]
 
  [Variables]
 
  VarName1=Description 1
 
  VarName1=Description 1
 
  VarName2=Description 2
 
  VarName2=Description 2
  
The variables found will be presented with their description in a dialog,  
+
Найденные переменные будут представлены с их описанием в диалоговом окне, и пользователь должен представить значение для переменных.
and the user must present a value for the variables.
 
  
The' 'project.ini'' file can contain a second section, called ''Project'', which
+
Файл ''project.ini'' может содержать второй раздел, называемый ''Project'', который может содержать некоторую информацию о проекте. Здесь можно найти следующие ключевые слова:
can contain some info about the project. The following keywords can be found
 
there:
 
  
 
==ProjectFile==
 
==ProjectFile==
Line 115: Line 103:
 
project.ini
 
project.ini
  
 +
<syntaxhighlight>
 
  [Variables]  
 
  [Variables]  
 
  MAINUNIT=Filename for the default unit.pas file
 
  MAINUNIT=Filename for the default unit.pas file
Line 123: Line 112:
 
  Author=Hansaplast
 
  Author=Hansaplast
 
  Description=Lazarus LCL form specifically for my needs
 
  Description=Lazarus LCL form specifically for my needs
 +
</syntaxhighlight>
  
 
__PROJNAME__.lpr:
 
__PROJNAME__.lpr:
  
program __PROJNAME__;
+
<syntaxhighlight> program __PROJNAME__;
 
   
 
   
 
  {$mode objfpc}{$H+}
 
  {$mode objfpc}{$H+}
Line 144: Line 134:
 
   Application.Run;
 
   Application.Run;
 
  end.
 
  end.
 +
</syntaxhighlight>
  
 
__MAINUNIT__.pas:
 
__MAINUNIT__.pas:
  
unit __MAINUNIT__;
+
<syntaxhighlight> unit __MAINUNIT__;
 
      
 
      
 
  {$mode objfpc}{$H+}
 
  {$mode objfpc}{$H+}
Line 175: Line 166:
 
  object __MAINFORM__: T__MAINFORM__
 
  object __MAINFORM__: T__MAINFORM__
 
  ...
 
  ...
 
+
</syntaxhighlight>
  
 
Keep in mind that this brief tutorial is just to get you started, the variable replacement mechanism offered can be utilized for many different purposes.
 
Keep in mind that this brief tutorial is just to get you started, the variable replacement mechanism offered can be utilized for many different purposes.

Revision as of 00:00, 22 December 2018

Template:MenuTranslate

Обзор

Вы можете приспособиться при создании новых проектов. Среда IDE позволяет регистрировать собственные типы проектов с помощью пакетов designtime. Пакет projtemplates ( он предварительно установлен в обычных бинарных пакетах Lazarus) позволяет просто использовать существующие проекты в качестве шаблонов.

Пакет projtemplates

Этот пакет реализует шаблоны проектов и поставляется с исходными кодами lazarus (components/projecttemplates/projtemplates.lpk).

Пакет поставляется с предустановленными бинарными пакетами Lazarus (например, установщик Windows). Этот пакет добавляет категорию в диалог File-New: Template projects

Он также добавляет пункт меню New project from Template в меню File, а также меню project template options в разделе Tools [общего] меню. Этот пункт меню отображается только в том случае, если каталог шаблонов (см. следующий абзац) существует и содержит хотя бы один подкаталог шаблонов.

В [разделе] Project template options можно выбрать каталог. Этот каталог должен содержать подкаталог для каждого шаблона. Каждый каталог шаблонов содержит шаблон для проекта: набор файлов, которые будут скопированы и использованы в качестве нового проекта.

Во время копирования пакет будет сканировать имена файлов/каталогов и содержимое файлов для подстановки переменных: __VARNAME__ будет заменено значением переменной VARNAME

По умолчанию движок знает о 2 переменных:

  • ProjDir: Каталог, в котором будет создан новый проект.
  • ProjName: Название проекта.

Дополнительные переменные должны быть определены в файле с именем project.ini в каталоге проекта. Это - файл в формате Windows INI.

Раздел [Variables] будет сканироваться на предмет имен переменных:

[Variables]
VarName1=Description 1
VarName2=Description 2

Найденные переменные будут представлены с их описанием в диалоговом окне, и пользователь должен представить значение для переменных.

Файл project.ini может содержать второй раздел, называемый Project, который может содержать некоторую информацию о проекте. Здесь можно найти следующие ключевые слова:

ProjectFile

Any file that has a name equal to this (no extension) is treated specially, it is renamed to the project name. That is ProjectFile=example will replace example.lpi, example.lpr and example.cfg with the name given by the user. By default, the value of ProjectFile is assumed to be project. (note that the .ini file is not copied)

Name

Name of the template. The Name and description will be presented in the 'File-New' dialog.

Author

Author of the template

Description

Short (one-line) description of the project. The Name and description will be presented in the 'File-New' dialog.

Recurse

A boolean value (1/0) which tells the engine to recurse in subdirectories or not.

Exclude

Comma separated list of filename extensions which should not be searched for keyword subsitution.

Getting Started

Step 1;

Create your own template directory (for example ~/.lazarus/mytemplates) and set this path in Lazarus (menu: Tools -> Project Template Options).

Step 2:

For any template functions to even appear in the Lazarus File menu, you will need at least one template which you can base on your existing (normal) project;

- Create a directory in your template directory (for example ~/.lazarus/mytemplates/myfirsttemplate)

- Copy your project files in this new directory (*.lfm, *.pas, *.ico, *.lpi, *.lpr, *.res)

Step 3:

Create a "project.ini" file in the new template directory.

The minimum should look something like this:

project.ini:

[Variables]

[Project] 
Name=My Form Template

Optional:

The nice thing of Project Templates is that it supports variables. Since a project will probably not be named the same as your example template you will have to do some code editing and file renaming.

Files: Rename the project file (ico, lpi, lpr, res) to __PROJNAME__.ext (where extension is the original extension of course). For example: project.lpi becomes __PROJNAME__.lpi. Note: the content of the lpi file might need some cleaning, for example removing history, reference to files, not sure if the lpi file is even needed.

File content: For all files that referred to project.lpi etc, change the content of your files so all "project" references become "__PROJNAME__" (with the quotes).

You can optionally define your own variables, for example to give the "unit.pas" a different filename. You could define for example __MAINUNIT__ and __MAINFORM__ in project.ini as MAINUNIT and MAINFORM - during creation Lazarus will ask you for these names. Now every occurrence of __MAINUNIT__, for example, will be replaced with the text you provided (avoid special characters and spaces).

Note that this works for all variables; Every occurrence of a variable in filenames and file content will be replaced by what you entered on creation of a new project based on your template. Predefined variables are PROJNAME and PROJDIR but I didn't find a purpose for PROJDIR just yet.

Some examples:

project.ini

 [Variables] 
 MAINUNIT=Filename for the default unit.pas file
 MAINFORM=Form name
 
 [Project]
 Name=My Custom Form
 Author=Hansaplast
 Description=Lazarus LCL form specifically for my needs

__PROJNAME__.lpr:

 program __PROJNAME__;
 
 {$mode objfpc}{$H+}
   
 uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Interfaces, // this includes the LCL widgetset
  Forms, __MAINUNIT__; 
   
 {$R *.res}
   
 begin
  Application.Initialize;
  Application.CreateForm(T__MAINFORM__, __MAINFORM__);
  Application.Run;
 end.

__MAINUNIT__.pas:

 unit __MAINUNIT__;
    
 {$mode objfpc}{$H+}
   
 interface
   
 uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
  Buttons, StdCtrls, LCLIntf, LCLType, ComCtrls;
   
 type
   
  { __MAINFORM__ }
   
  T__MAINFORM__ = class(TForm)
   
 ...
   
 procedure T__MAINFORM__.FormPaint(Sender: TObject);
 ...
   
 //etc


__MAINUNIT__.lfm:

 object __MAINFORM__: T__MAINFORM__
 ...

Keep in mind that this brief tutorial is just to get you started, the variable replacement mechanism offered can be utilized for many different purposes. For example to define a form caption, a copyright statement, a web link on your forms, specific objects, etc. --Hansaplast 16:30, 4 August 2012 (UTC)