Сегодня: 18:12:2025 Доброй вам ночи!

I live ExBB and CMS Limbo!  I live ExBB and CMS Limbo!
Логин :
Пароль :
Регистрация?  Забыли пароль? 
 

Страниц (117): В начало « ... 48 49 50 51 [52] 53 54 55 56 ... » В конец

> Найдено сообщений: 1165
NordWest Отправлено: 8 января 2017 — 02:32 • Тема: Самодельный корпус для компьютера • Форум: Сделай сам

Ответов: 5
Просмотров: 12424
Можно и так... Но наверное пылиться будет больше.
NordWest Отправлено: 7 января 2017 — 00:46 • Тема: Создание собственного функционала • Форум: SMF Community

Ответов: 0
Просмотров: 2008

Вступление

Начиная с SMF версии 2.0 для добавления пользовательских функций не требуется каких-либо изменений в "основной" код.
Теперь для этого достаточно просто создать несколько отдельных файлов и написать соответствующий интеграционный обработчик.

Для понимания, как это работает в SMF, давайте взглянем, что обычно происходит при выполнении кода. Запуск корневого файла index.php приводит в частности к созданию массива $actionArray, где определены все стандартные функции SMF (например календарь, почта и т.д.).

Структура элементов этого массива следующая:
code:
'myaction' => array('myaction_file.php', 'myaction_function'),
где:
myaction - это название функции, для использования в URL (например http://www.yourdomain.tld/forum/index.php?action=myaction),
myaction_function - это функция, которую SMF должен будет вызвать,
myaction_file.php - это файл, который содержит функцию myaction_function.

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

Допустим для данного примера решили, что:
действие - youraction
функция - YourActionMain
файл - YourAction.php
Для удобства восприятия в дальнейшем мы эти параметры выделим красным цветом.


Создаём интеграционный файл


Назначением интеграционного файла по сути является внесение нужных изменений в базу данных. Этот файл запускается однократно, после чего его лучше с форума удалить. Для упрощения процедуры в SMF существует функция add_integration_function . Создадим чистый PHP файл с произвольным именем, например add_action_hook.php. В этот файл необходимо внести примерно такой код:

PHP:
<?php
// Если SSI.php находится в том же месте, что и файл, а переменная SMF не определена, то подключаем файл.
if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('SMF'))
require_once(dirname(__FILE__) . '/SSI.php');
// Хмм... нет SSI.php и не определена переменная SMF?
elseif (!defined('SMF'))
die('<b>Ошибка:</b> Интеграция не удалась! Пожалуйста убедитесь, что вы поместили этот файл рядом с корневым index.php.');

add_integration_function('integrate_pre_include', '$sourcedir/Subs-YourAction.php');
add_integration_function('integrate_actions', 'youraction_add_hook');
?>

Как можно увидеть в коде присутствуют два интеграционных вызова:
integrate_pre_include - определяет файл, который содержит функцию youraction_add_hook
integrate_actions - определяет функцию, которая будет добавлена в массив $actionArray.


Создаем файлы с кодом


./Sources/Subs-YourAction.php

Этот файл должен содержать функцию youraction_add_hook. Он будет подгружаться каждый раз при вызове SMF, чтобы добавить наше действие в общий список. Этот файл должен быть помещен в каталог /Sources/.

Код данного файла должен быть примерно таким:
PHP:
<?php
if (!defined('SMF')) die('Hacking attempt...');

function youraction_add_hook(&$actionArray)
{
$actionArray['youraction'] = array('YourAction.php', 'YourActionMain');
}

?>

./Sources/YourAction.php
Этот файл должен содержать функцию YourActionMain, срабатывающую при вызове youraction. Он так же должен быть помещен в каталог /Sources/.

Содержимое файла должно содержать по крайней мере одну функцию:
PHP:
<?php
if (!defined('SMF')) die('Hacking attempt...');

function YourActionMain()
{

}
?>

Эта функция может включать в себя загрузку шаблона YourAction.template.php например так:
code:
loadTemplate('YourAction');

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

В результате окончательный YourAction.php должен выглядеть примерно следующим образом:
PHP:
<?php
if (!defined('SMF')) die('Hack Attempt...');

function YourActionMain()
{

// Прежде всего необходимо дать доступ ко всем нужным глобальным переменным
global $context, $scripturl, $txt, $smcFunc;

// Затем загрузить нужный для этого действия шаблон
loadTemplate('YourAction');

//Потом определить заголовок для главной страницы
$context['page_title'] = $txt['youraction_PageTitle'];
$context['page_title_html_safe'] = $smcFunc['htmlspecialchars'](un_htmlspecialchars($context['page_title']));


//Затем определить древо ссылок
$context['linktree'][] = array(
'url' => $scripturl. '?action=youraction',
'name' => $txt['your_action'],
);

//И наконец начать делать действия по выводу нужной информации
//Результаты этого вывода хранятся в массиве $context.
$context['youraction_Head'] = $txt['youraction'];
$context['youraction_Body'] = 'Hello World';

}

?>


Создаем шаблон


./Themes/default/YourAction.template.php
Как уже объяснялось ранее, файл YourAction.template.php должен содержать функцию шаблона, в данном случае template_main:
PHP:
<?php
function template_main()
{

}
?>

Эта функция используется для отображения выходных данных при вызове действия youraction, и предназначена для создания выходных HTML данных посредством оператора echo.

Если предполагается создать заголовок и раздел с содержимым, нужно будет использовать примерно следующий код:
PHP:
<?php
function template_main()
{

// Объявляем нужные глобальные переменные
global $context;

// Определяем заголовок класса "catbg"
echo '<div class="cat_bar">
<h3 class="catbg">', $context['youraction_Head'], '</h3>
</div>';

//Определяем содержимое классом "windowbg2"
echo '<div class="windowbg2">
<span class="topslice"><span></span></span>
<div class="content">', $context['youraction_Body'], '</div>
<span class="botslice"><span></span></span>
</div><br />';

}

?>

Файл YourAction.template.php должен быть помещен в каталог /Themes/default/.

Языковые файлы


./Themes/default/languages/Modifications.russian.php

Файлы вида Modifications.languages.php обычно используются для того, чтобы добавить новые строки в массив $txt. Таким образом можно легко перевести любой мод SMF на другие языки. Все эти файлы необходимо помещать в /Themes/default/languages/.

Чтобы добавить новую строку в массив $txt, достаточно добавить этот код:
PHP:
// Ваши языковые переменные
$txt['youraction'] = 'Новая функция';
$txt['youraction_PageTitle'] = 'Заголовок страницы новой функции';

в файл Modification.russian.php или Modification.russian-utf8.php (в зависимости от нужной кодировки) и сохранить его.

./Themes/default/languages/Who.russian.php

Присутствующие в Modification.russian.php строки будут доступны повсюду в коде SMF. В некоторых случаях может быть полезно, чтобы некоторые строки были доступны только при определённых вызовах. Такие строки можно добавить в другие языковые файлы. Рассмотрим к примеру файл Who.russian.php - это файл подключается только тогда, когда кто-то обращается к странице через действие ?action=who .

После открытия файла нужно добавить в конец файла примерно такой код:
PHP:
// Моя функция на странице "Кто онлайн"
$txt['whoall_youraction'] = 'Использует <a href="' . $scripturl . '?action=youraction">Новая функция</a>.';

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

Осуществляем интеграцию


Загрузите ранее подготовленный файл add_action_hook.php в корневой каталог вашего форума (тот же каталог, который содержит SSI.php), а затем перейдите вашим браузером по ссылке httр://yourdomain.tld/forum/add_action_hook.php.

Если вы не получили каких-либо сообщений об ошибках, и вы видите пустую страницу - все прошло успешно, и вы можете удалить add_action_hook.php с сервера.

Смотрим результат


Перейдите в браузере по ссылке httр://yourdomain.tld/forum/index.php?action=youraction и вы должны увидеть на экране результат вашего действия!

Удаление интеграции


Чтобы удалить интеграцию, нужно выполнить два следующих действия:
1. Удалить все связанные файлы.
2. Удалить обработчики интеграции.

Для удаления обработчиков интеграции можно использовать файл, аналогичный add_action_hook.php, он может называться called remove_action_hook.php и должен содержать этот код:
PHP:
<?php
// Если SSI.php находится в том же месте, что и файл, а переменная SMF не определена, то подключаем файл.
if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('SMF'))
require_once(dirname(__FILE__) . '/SSI.php');
// Хмм... нет SSI.php и не определена переменная SMF?
elseif (!defined('SMF'))
die('<b>Ошибка:</b> Удаление не удалось! Пожалуйста убедитесь, что вы поместили этот файл рядом с корневым index.php.');

remove_integration_function('integrate_pre_include', '$sourcedir/Subs-YourAction.php');
remove_integration_function('integrate_actions', 'youraction_add_hook');
?>

Файл должен быть загружен в корневой каталог форума, после чего вызван браузером по ссылке http://yourdomain.tld/forum/remove_action_hook.php, а затем удалён с сервера так же, как и add_action_hook.php.

Оригинал статьи расположен здесь.
NordWest Отправлено: 6 января 2017 — 23:53 • Тема: Назначение файлов • Форум: SMF Community

Ответов: 99
Просмотров: 55914
Admin.php - Handles basic administration functions.

BoardIndex.php - The functions in this file are used to display the board index.

Calendar.php - This file contains functions used for displaying the calendar

Class-Package.php - Contains the ftp_connection and xmlArray classes. The ftp_connection class contains functions for FTP-related file management, while the xmlArray class is a simple XML DOM parser. Both classes were located in Subs-Packages.php in previous versions of SMF. Note: The xmlArray functions documented here are the only ones that can be called from outside the class.

DbExtra-mysql.php - This file contains rarely used extended database functionality. Most of the functions in this file deal with creating database dumps. The functions in this file are only used for MySQL.

DbExtra-postgresql.php - This file contains rarely used extended database functionality. Most of the functions in this file deal with creating database dumps. The functions in this file are only used for PostgreSQL.

DbExtra-sqlite.php - This file contains rarely used extended database functionality. The functions in this file are used for SQLite

DbPackages-mysql.php - This file contains functions specifically designed to be utilized by packages. This file is used for MySQL databases.

DbPackages-postgresql.php - This file contains functions specifically designed to be utilized by packages. This file is used for PostgreSQL databases.

DbPackages-sqlite.php - This file contains functions specifically designed to be utilized by packages. This file is used for SQLite databases.

DbSearch-mysql.php - Contains functions for handling various search-related functions.

DbSearch-postgresql.php - Contains functions needed for handling search-related functionality in PostgreSQL.

DbSearch-sqlite.php - Contains functions for handling search-related functionality in SQLite

Display.php - This is perhaps the most important and probably most accessed files in all of SMF. This file controls topic, message, and attachment display.

DumpDatabase.php - This file handles database backups.

Errors.php - This important file contains functions for handling and logging errors.

Groups.php - This file currently just shows group info, and allows certain privileged members to add/remove members.

Help.php - This file handles the nifty little admin help popup boxes and the user help pages.

Karma.php - This file handles smiting and applauding.

Load.php - This is probably one of the most important files in SMF. It is responsible for loading just about all data that is used by SMF - member info, permissions, boards, etc. It also handles all session-related operations, censored text and (in 1.1) caching.

LockTopic.php - This file handles locking and stickying of topics.

LogInOut.php - This file is concerned pretty much entirely, as you see from its name, with logging in and out members, and the validation of that.

ManageAttachments.php - This file handles a lot of admin functions for managing attachments and uploaded avatars.

ManageBans.php - This file contains all the functions needed for the ban center.

ManageBoards.php - This file controls all the admin functions for managing and editing boards.

ManageCalendar.php - Contains functions for managing holidays, events and various calendar-related options and settings.

ManageErrors.php - This file handles the error log and the deletion of said errors.

ManageMail.php - This file is all about mail, how we love it so. In particular it handles the admin side of mail configuration, as well as reviewing the mail queue - if enabled.

ManageMaintenance.php - This file contains functions for various forum maintenance tasks.

ManageMembergroups.php - This file contains all the functions necessary for membergroup management in the admin center. Many of the functions in this file are found in ManageMembers.php in 1.0.x

ManageMembers.php - Contains functions necessary for managing members. In 1.0.x, this file also contains functions for managing membergroups and various other member-related functions.

ManageNews.php - This file is responsible for handling everything in the &quot;News and Newsletters&quot; section of the admin center.

ManagePaid.php - This file contains functions for managing paid subscriptions and related settings.

ManagePermissions.php - ManagePermissions handles all possible permission stuff.

ManagePosts.php - This file contains all the screens for managing Posts and Topics settings.

ManageRegistration.php - This file helps the administrator setting registration settings and policy as well as allow the administrator to register new members themselves.

ManageScheduledTasks.php - Handles everything related to scheduled tasks.

ManageSearch.php - Handles all the functionality related to search settings in the admin center.

ManageSearchEngines.php - Contains functions for handling features and options related to search engines

ManageServer.php - This file contains all the functionality needed to edit the core server settings.

ManageSettings.php - Этот файл содержит функции для управления различными настройками форума, а также страницы для «Настройки модов».

ManageSmileys.php - This file contains functions for managing smileys and smiley sets.

Memberlist.php - This file handles the main (publicly-viewable) memberlist, as well as searching for members via the memberlist.

MessageIndex.php - Loads up a list of topics (and child boards) in a particular board and displays them.

ModLog.php - This file is responsible for the Moderation Log.

MoveTopic.php - Contains functions for moving one or more topics.

News.php - Contains functions for all of the news feeds.

Notify.php - This file contains just the functions that turn on and off notifications to topics or boards.

PackageGet.php - This whole file deals with package servers and downloading/uploading new packages.

Packages.php - This important file handles a lot of things related to the package manager.

PersonalMessage.php - Contains functions for handling the PM center. File was called InstantMessage.php in 1.0.x

Poll.php - This file contains the functions for voting, locking, removing and editing polls. Posting of polls is handled by Post.php...

Post.php - The job of this file is to handle everything related to posting replies, new topics, quotes, and modifications to existing posts. It also handles quoting posts by way of a popup.

Printpage.php - This file contains just one function that formats a topic to be printer friendly.

Profile-Actions.php - This file contains profile action functions.

Profile-Modify.php - This file has the primary job of showing and editing people\'s profiles. It also allows the user to change some of their or another\'s preferences, and such things

Profile-View.php - This file contains functions dealing with the actual viewing of a user\'s profile.

Profile.php - This file handles all of the profile-related functionality.

QueryString.php - This file does a lot of important stuff. Mainly, this means it handles the query string, request variables, and session management.

Recent.php - This file had one very clear purpose. It is here expressly to find and retrieve information about recently posted topics, messages, and the like.

Register.php - This file has two main jobs, but they really are one. It registers new members, and it helps the administrator moderate member registrations. Similarly, it handles account activation as well.

Reminder.php - This file deals with all the &quot;Forgot your password?&quot; things.

RemoveTopic.php - This file handles removing topics and posts.

RepairBoards.php - This file is solely responsible for handling the Find and Repair Any Errors maintenance task.

Reports.php - This file is exclusively for generating reports to help assist forum administrators keep track of their forum configuration and state. The core report generation is done in two areas. Firstly, a report &quot;generator&quot; will fill context with relevant data. Secondly, the choice of sub-template will determine how this data is shown to the user.

ScheduledTasks.php - Handles all of the scheduled tasks

Search.php - This file handles all of the search things.

SearchAPI-Custom.php - A class and methods for interfacing with the custom search index

SearchAPI-Fulltext.php - Contains methods for handling searches using MySQL\'s fulltext index.

SearchAPI-Standard.php - Standard search. Doesn\'t use an index.

Security.php - This file has the very important job of insuring forum security. This task includes banning and permissions, namely.

SendTopic.php - This file handles the &quot;send topic&quot; and &quot;report to moderator&quot; features.

SplitTopics.php - This file handles merging and splitting topics.

SSI.php - Contains nearly 30 functions designed to make integration with your forum simple and easy. By including this file in your code, you gain full access to SMF and all its functions...

Stats.php - Loads up all the information for the forum statistics

Subs-Admin.php - Contains a few handy admin functions.

Subs-Auth.php - This file contains functions relating to authentication, user handling and the like.

Subs-BoardIndex.php - Contains one function which loads all the data for the boardindex and messageindex.

Subs-Boards.php - This file is mainly concerned with minor tasks relating to boards, such as marking them read, collapsing categories, or quick moderation.

Subs-Calendar.php - This file contains several functions for retrieving and manipulating calendar events, birthdays and holidays.

Subs-Categories.php - This file contains the functions to add, modify, remove, collapse and expand categories.

Subs-Charset.php - Contains functions dealing with character sets and string manipulation, mostly dealing with UTF-8.

Subs-Compat.php - This file provides compatibility functions and code for older versions of PHP, such as the sha1() function. It is only included for those older versions.

Subs-Db-mysql.php - This file has all the main functions in it that relate to the database. These functions are used for MySQL databases.

Subs-Editor.php - This file contains those functions specific to the editing box and is generally used for WYSIWYG type functionality.

Subs-Graphics.php - Contains many graphics-related functions for attachments and uploaded avatars.

Subs-List.php - Handles the creation of lists of data.

Subs-Membergroups.php - This file contains functions regarding manipulation of and information about membergroups.

Subs-Members.php - This file contains some useful functions for members and membergroups. Many of these functions are in either ManageMembers.php or ManageMembergroups.php in 1.0.x.

Subs-MembersOnline.php - This file currently only holds the function for showing a list of online users used by the board index and SSI. In the future it\'ll also contain functions used by the Who\'s online page.

Subs-Menu.php - This file contains functions for handling and displaying menus throughout SMF.

Subs-Package.php - This file\'s central purpose of existence is that of making the package manager work nicely. It contains functions for handling tar.gz and zip files, as well as a simple xml parser to handle the xml package stuff. Not to mention a few functions to make file handling easier.

Subs-Post.php - This file contains those functions pertaining to posting, and other such operations, including sending emails, PMs, blocking spam, preparsing posts, spell checking, and the post box.

Subs-Recent.php - Contains two functions related to getting recent posts...

Subs-Sound.php - This file handles sound processing. In order to make sure the visual verification is still accessible for all users, a sound clip is being addded that reads the letters that are being shown.

Subs.php - With more than 30 functions that relate to nearly everything, this file is one of the largest and most important files in SMF.

Themes.php - This file concerns itself almost completely with theme administration. Its tasks include changing theme settings, installing and removing themes, choosing the current theme, and editing themes.

ViewQuery.php - This file is concerned with viewing queries, and is used for debugging (ie when the &quot;db_show_debug&quot; variable is enabled in Settings.php)

Who.php - This file handles the Who\'s Online list.

Более полное описание смотри здесь.
NordWest Отправлено: 6 января 2017 — 23:21 • Тема: Описание структуры файла package-info.xml • Форум: SMF Community

Ответов: 0
Просмотров: 2068
Для начала определимся с терминологией:
element или tag: в теги заключены инструкции для установщика, указывающие, что ему делать, например <install></install>
attribute или property: дополнительный параметр в тегах, конкретизирующий инструкцию
inline: код или текст, который будет подлежать замене
file: имя файла, который подлежит изменению
location или path: путь к файлу или директории

Так же следует пояснить смысл некоторых переменных
$boarddir: Корневой каталог форума. Обычно это каталог, в котором расположен index.php
$sourcedir: Путь к каталогу Sources в котором расположены основные файлы движка (например Post.php, Admin.php и другие)
$avatardir: Путь к каталогу Avatars в котором расположены аватары.
$themedir: Путь к каталогу с текущей темой оформления
$themes_dir: Путь к каталогу со всеми темами
$imagesdir: Путь к директории с рисунками, используемые в выбранной теме
$languagedir: Путь к директории с языковыми файлами
$smileysdir: Путь к директории со смайлами

package-info.xml

Все элементы не являются обязательными и не содержат атрибутов, если это не указано явным образом.

<package-info></package-info>
Головной тег. Должен охватывать все остальные элементы в файле.
Атрибуты:
xmlns: по умолчанию "http://www.simplemachines.org/xml/package-info"; не обязателен

<id></id>
Contains the id of the package. Should be in the format of [username]:[package name]. For instance sleepy:LeetMod When submitting a mod to the mod site, the username should be your username from www.simplemachines.org

<name></name>
Contains the name of the package.

<type></type>
The type of package - "avatar", "language", or "modification".

<version></version>
The package's current version.

<install></install>, <upgrade></upgrade>, and <uninstall></uninstall>
Actions taken on installation. The elements and their attributes are the same for the install, upgrade, and uninstall elements.

Attributes:
for: What versions to install/upgrade/uninstall for. Comma delimited string with ranges such as "1.0-1.5,2.0"; optional
from: Upgrade Only; What mod versions they are upgrading from. Comma delimited string with ranges such as "1.0-1.5,2.0"; optional

Теги:
<readme></readme> или <readme /> (используется только если type="file")
Текст с описанием или имя файла, содержащего описание
Не обязателен: Да
Атрибуты:
lang: указание для какого языка использовать; не обязателен
parsebbc: следует ли анализировать в файле bbcode; не обязателен; по умолчанию - false
type: тип "inline" или "file"; по умолчанию "file"; не обязателен
Примеры:
<readme type="inline" parsebbc="true" lang="russian">[center][glow=black,2,300][size=16pt]Это текст описания[/size][/glow]</readme>
<readme type="file" parsebbc="true">readme.txt</readme>

<code></code> or <code /> (for use with type="file" only)
Filename of a php file to be executed.
Deprecated use in SMF 2.0, please use <database> in SMF 2.0 or higher
Optional: Yes
Attributes:
type: "inline" or "file"; defaults to "file"; optional

<database></database> or <database /> (for use with type="file" only)
Filename of a database code to be executed.
Only exists in SMF 2.0 or higher
Optional: Yes
Attributes:
type: "inline" or "file"; defaults to "file"; optional

<modification></modification> or <modification /> (for use with type="file" only)
Instructions to take for a modification.
Optional: Yes
Attributes:
type: if "inline", you may use the <file>, <operation>, <search>, and <add> elements listed in the modification.xml documentation."inline" or "file"; defaults to "file"; optional
reverse: reverse the instructions; "true" or "false"; defaults to "false"; optional
format: this documentation only covers xml formatted modifications and it is recommended that you use this format; "xml" or "boardmod"; defaults to "xml"; optional

<create-dir />
Create a new directory.
Optional: Yes
Attributes:
name: the name of the directory
destination: the path of the directory where you want to create this new directory

<create-file />
Create a blank file.
Optional: Yes
Attributes:
name: the name of the file
destination: the path of the directory where you want to create this new file

<require-dir />
Require a directory and all files in it from inside the package.
Optional: Yes
Attributes:
from: the path to the directory
name: the name of the directory
destination: the path of where you want to put this directory

<require-file />
Require a file from inside the package.
Optional: Yes
Attributes:
from: the path to the file
name: the name of the file
destination: the path of where you want to put this file

<move-dir />
Move an entire directory. May also be used to rename a directory by moving it to it's parent directory with a different name.
Optional: Yes
Attributes:
from: the path of the directory you want to move
name: the name of the directory
destination: the path to where you want to put the directory

<move-file />
Move a file. May also be used to rename a file by moving it to it's parent directory with a different name.
Optional: Yes
Attributes:
from: the path of the file you want to move
name: the name of the file
destination: the path to where you want to put the file

<remove-dir />
Remove a directory and all files in it.
Optional: Yes
Attributes:
name: the name and path of the directory to be removed

<remove-file />
Remove a file.
Optional: Yes
Attributes:
name: the name and path of the file to be removed

<redirect></redirect> or <redirect />
Redirect after install/upgrade/uninstall.
Optional: Yes
Attributes:
url: the url to redirect to; Required. "$boardurl", "$scripturl", and "$session_id" are accepted.
type: inline or file. Whether to use a file or inline text for redirect text.
timeout: Time until the redirect occurs. Default: 5 seconds

Например:
<redirect url="?action=admin;area=maintain;sa=routine;activity=cleancache" timeout="3000"></redirect>
NordWest Отправлено: 6 января 2017 — 20:28 • Тема: Слои в SMF • Форум: SMF Community

Ответов: 0
Просмотров: 2053
Слои (layers) — функции, содержащие некоторую часть шаблона.

Чтобы увидеть текущие слои, зайдите на форум как администратор и добавьте к адресу параметр ?debug, например
code:
http://mysite.ru/index.php?debug


Текущие слои выделятся рамочкой.

Верхний слой html_above содержит шапку шаблона. Подвал содержится в слое html_below. В слоях body_above и body_below содержится тело страницы. Загляните в index.template.php и поищите функции с окончанием _above, _below — стандартные слои шаблона.

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

Для начала создадим шаблон Your.template.php с таким содержимым
code:
function template_namefunction_above()
{
// тут ваш код
}

function template_namefunction_below()
{
// и тут ваш код
}


и поместим его в папку /Themes/default

 Цитата:
Вместо namefunction можно использовать любое имя (конечно же, на латинице).


Теперь, если требуется разместить блок в верхней части шаблона, html-контент добавляется в функцию template_namefunction_above, а для добавления в нижнюю часть — в функцию template_namefunction_below. Никто не запрещает использовать обе функции даже с одинаковым содержимым.

 Цитата:
Внимание!!!
В файле наличие обоих функций template_namefunction_above и template_namefunction__below обязательно, иначе получим ошибку.


Затем, чтобы подключить наш шаблон к общему шаблону, добавим в нужный файл его вызов:
code:
loadTemplate('Your'); // подключение файла Your.template.php
$context['template_layers'][] = 'namefunction'; // вызов функций из подключенного шаблона


После этого созданные слои отобразятся после встроенных слоев SMF

Оригинал статьи находится здесь.
NordWest Отправлено: 6 января 2017 — 19:21 • Тема: Новости дня • Форум: Всё подряд

Ответов: 276
Просмотров: 91258
Farmer
Александр Анатольевич, а можно узнать, что там в беседке то произошло, что вы перестали там бывать? Вот честное слово - как то этот момент пропустил...
NordWest Отправлено: 1 января 2017 — 15:09 • Тема: Новости дня • Форум: Всё подряд

Ответов: 276
Просмотров: 91258
 Цитата от Farmer:
А что нового у Вас,как зима,самолеты летают.Как супруга после утраты!?

Да всё потихоньку. Правда работы прибавилось. У нас собственник сменился - всех людей поразогнали, теперь приходится работать за себя и за того парня.
Что касается супруги... Ну так скоро уже год как случилось - время лечит.
NordWest Отправлено: 31 декабря 2016 — 04:15 • Тема: Новости дня • Форум: Всё подряд

Ответов: 276
Просмотров: 91258
Ура, наш Дед вернулся!!! Жутко рад вас видеть!!! Ура!
Как дела, как деревня? Всем родным большущий привет и мои искренние пожелания здоровья и удачи в новом году! Улыбка
NordWest Отправлено: 24 декабря 2016 — 23:03 • Тема: Самодельный датчик движения воды • Форум: Сделай сам

Ответов: 0
Просмотров: 2060
Этим летом купил через интернет родителям недорогой проточный водонагреватель.



Цель - обеспечить возможность умываться и мыть посуду тёплой водой в период летнего отключения горячей воды на профилактику. Устанавливать накопительный бак для этих целей считаю нецелесообразным, т.к. стОит дорого, занимает много места и есть опастность, что однажды проржавеет и потечёт. Однако дешевизна оказалась с подвохом - в купленном водонагревателе отсутствовал контроль движения воды. В инструкции было написано, что необходимо сначала открыть воду и только потом включать нагреватель. Выключать следовало в обратном порядке. Если включить нагреватель не открыв воду - нагреватель перегреется и сгорит.

Короче в таком виде этот нагреватель мне не подходил. Либо продавать, либо дорабатывать.

Решил дорабатывать... (Показать)
NordWest Отправлено: 23 декабря 2016 — 08:50 • Тема: Новости дня • Форум: Всё подряд

Ответов: 276
Просмотров: 91258
 Цитата от topinant:
Так что был бы благодарен за науку.
Да я сам по сути валенок, просто современные возможности настолько всё упростили, что элементарным программированием может заниматься даже ребёнок.

Буду выкладывать статьи со своими "разработками", за одно и пообсуждаем общие темы...

Страниц (117): В начало « ... 48 49 50 51 [52] 53 54 55 56 ... » В конец

Powered by ExBB v1.1.180311