Выбор отдельного шаблона для новостей

Выбор отдельного шаблона для новостей

Здравствуйте! Продолжаю тему вывода новостей на сайте. Сегодня хочу предложить Вашему вниманию хак, позволяющих при публикации новостей выбирать отдельный и уникальный шаблон для неё. Этот хак пригодится тем, кому необходимо выделить определенные новости, что бы привлечь внимание посетителей именно на них или просто, что бы разнообразить вывод новостей на сайте.
Установка данного хака:

1. Выполняем запросы к базе данных:
ALTER TABLE `dle_post` ADD `show_tpl` VARCHAR( 40 ) NOT NULL DEFAULT '';
ALTER TABLE `dle_post` ADD `full_tpl` VARCHAR( 40 ) NOT NULL DEFAULT '';
Создаем папку templates/Ваш шаблон/show и загружаем в нее tpl шаблоны которые Вы будите использовать в новостях.

2. Открываем engine/inc/addnews.php
Находим:
if( ! $user_group[$member_id['user_group']]['admin_addnews'] ) {
    msg( "error", $lang['index_denied'], $lang['index_denied'] );
}
Ниже вставляем:
if( $handle = opendir( ROOT_DIR . '/templates/' . $config['skin'] . '/show' ) )
{
    while( false !== ( $file = readdir( $handle ) ) )
    {
        $file = substr( $file, 0, -4 );
        
        if ( file_exists( ROOT_DIR . '/templates/' . $config['skin'] . '/show/' . $file . '.tpl' ) )
            $template[] = $file;
    }

    closedir( $handle );
    
    sort( $template );
}
Находим:
    else $fix_br = "";
Ниже встваляем:
    $templ = '<option value="">---</option>';
        
    foreach ( $template as $value ) $templ .= '<option value="' . $value . '">' . $value . '.tpl</option>';
Находим:
        <tr>
            <td>&nbsp;</td>
            <td>{$lang['add_metatags']}<a href="#" class="hintanchor" onmouseover="showhint('{$lang['hint_metas']}', this, event, '220px')">[?]</a></td>
        </tr>
Ниже вставляем:
        <tr>
            <td height="29" style="padding-left:5px;">Шаблон для краткой новости:</td>
            <td><select name="short_tpl" id="short_tpl" style="width:388px;" class="edit">$templ</select></td>
        </tr>
        <tr>
            <td height="29" style="padding-left:5px;">Шаблон для полной новости:</td>
            <td><select name="full_tpl" id="full_tpl" style="width:388px;" class="edit">$templ</select></td>
        </tr>
Находим:
    $title = $db->safesql( $title );
Ниже вставляем:
    $short_tpl = $db->safesql( trim( totranslit( $_POST['short_tpl'] ) ) );
    $full_tpl = $db->safesql( trim( totranslit( $_POST['full_tpl'] ) ) );
        
    if ( $short_tpl != '' AND ! in_array( $short_tpl, $template ) ) $stop .= '<li>Шаблон краткой новости выбран не верно!</li>';
    if ( $full_tpl != '' AND ! in_array( $full_tpl, $template ) ) $stop .= '<li>Шаблон полной новости новости выбран не верно!</li>';
Находим:
    $db->query( "INSERT INTO " . PREFIX . "_post (date, autor, short_story, full_story, xfields, title, descr, keywords, category, alt_name, allow_comm, approve, allow_main, fixed, allow_rate, allow_br, votes, access, symbol, flag, tags, metatitle) values ('$thistime', '{$member_id['name']}', '$short_story', '$full_story', '$filecontents', '$title', '{$metatags['description']}', '{$metatags['keywords']}', '$category_list', '$alt_name', '$allow_comm', '$approve', '$allow_main', '$news_fixed', '$allow_rating', '$allow_br', '$add_vote', '$group_regel', '$catalog_url', '1', '{$_POST['tags']}', '{$metatags['title']}')" );
Заменяем на:
    $db->query( "INSERT INTO " . PREFIX . "_post (date, autor, short_story, full_story, xfields, title, descr, keywords, category, alt_name, allow_comm, approve, allow_main, fixed, allow_rate, allow_br, votes, access, symbol, flag, tags, metatitle, short_tpl, full_tpl) values ('$thistime', '{$member_id['name']}', '$short_story', '$full_story', '$filecontents', '$title', '{$metatags['description']}', '{$metatags['keywords']}', '$category_list', '$alt_name', '$allow_comm', '$approve', '$allow_main', '$news_fixed', '$allow_rating', '$allow_br', '$add_vote', '$group_regel', '$catalog_url', '1', '{$_POST['tags']}', '{$metatags['title']}', '$short_tpl', '$full_tpl')" );
Открываем engine/inc/editnews.php
Находим:
if ( ! $user_group[$member_id['user_group']]['admin_editnews'] ) {
    msg( "error", $lang['addnews_denied'], $lang['edit_denied'] );
}
Ниже вствляем:

if( $handle = opendir( ROOT_DIR . '/templates/' . $config['skin'] . '/show' ) )
{
    while( false !== ( $file = readdir( $handle ) ) )
    {
        $file = substr( $file, 0, -4 );
        
        if ( file_exists( ROOT_DIR . '/templates/' . $config['skin'] . '/show/' . $file . '.tpl' ) )
            $template[] = $file;
    }

    closedir( $handle );
    
    sort( $template );
}
Находим:
    else $fix_br = "";
Ниже вствляем:
    $short_tpl = '<option value="">---</option>';
        
    foreach ( $template as $value )
    {
        $short_tpl .= '<option value="' . $value . '"';
        
        if ( $value == $row['short_tpl'] ) $short_tpl .= 'selected="selected"';
        
        $short_tpl .= '>' . $value . '.tpl</option>';
    }
    
    $full_tpl = '<option value="">---</option>';
        
    foreach ( $template as $value )
    {
        $full_tpl .= '<option value="' . $value . '"';
        
        if ( $value == $row['full_tpl'] ) $full_tpl .= 'selected="selected"';
        
        $full_tpl .= '>' . $value . '.tpl</option>';
    }
Находим:
        <tr>
            <td>&nbsp;</td>
            <td>{$lang['add_metatags']}<a href="#" class="hintanchor" onmouseover="showhint('{$lang['hint_metas']}', this, event, '220px')">[?]</a></td>
        </tr>
Ниже вставляем:
        <tr>
            <td height="29" style="padding-left:5px;">Шаблон для краткой новости:</td>
            <td><select name="short_tpl" id="short_tpl" style="width:388px;" class="edit">$short_tpl</select></td>
        </tr>
        <tr>
            <td height="29" style="padding-left:5px;">Шаблон для полной новости:</td>
            <td><select name="full_tpl" id="full_tpl" style="width:388px;" class="edit">$full_tpl</select></td>
        </tr>
Находим:
    $title = $db->safesql( $title );
Ниже вставляем:
    $short_tpl = $db->safesql( trim( totranslit( $_POST['short_tpl'] ) ) );
    $full_tpl = $db->safesql( trim( totranslit( $_POST['full_tpl'] ) ) );
        
    if ( $short_tpl != '' AND ! in_array( $short_tpl, $template ) ) $stop .= '<li>Шаблон краткой новости выбран не верно!</li>';
    if ( $full_tpl != '' AND ! in_array( $full_tpl, $template ) ) $stop .= '<li>Шаблон полной новости новости выбран не верно!</li>';    
Находим запросы к базе содержащие:
set title='$title',
Заменяем этот участок на
set title='$title', short_tpl='$short_tpl', full_tpl='$full_tpl',

3. Открываем engine/modules/addnews.php
Находим:
} else {
Ниже вствляем:
    if( $handle = opendir( ROOT_DIR . '/templates/' . $config['skin'] . '/show' ) )
    {
        while( false !== ( $file = readdir( $handle ) ) )
        {
            $file = substr( $file, 0, -4 );
        
            if ( file_exists( ROOT_DIR . '/templates/' . $config['skin'] . '/show/' . $file . '.tpl' ) )
                $template[] = $file;
        }

        closedir( $handle );
    
        sort( $template );
    }
Находим:
        $alt_name = trim( $parse->process( stripslashes( $_POST['alt_name'] ) ) );
Ниже вствляем:
        $short_tpl = $db->safesql( trim( totranslit( $_POST['short_tpl'] ) ) );
        $full_tpl = $db->safesql( trim( totranslit( $_POST['full_tpl'] ) ) );
        
        if ( $short_tpl != '' AND ! in_array( $short_tpl, $template ) ) $stop .= '<li>Шаблон краткой новости выбран не верно!</li>';
        if ( $full_tpl != '' AND ! in_array( $full_tpl, $template ) ) $stop .= '<li>Шаблон полной новости новости выбран не верно!</li>';
Находим запросы к базе содержащие:
set title='$title',
Заменяем этот участок на
set title='$title', short_tpl='$short_tpl', full_tpl='$full_tpl',
Находим:
$db->query( "INSERT INTO " . PREFIX . "_post (date, autor, short_story, full_story, xfields, title, keywords, category, alt_name, allow_comm, approve, allow_main, fixed, allow_rate, allow_br, flag, tags) values ('$thistime', '$member_id[name]', '$short_story', '$full_story', '$filecontents', '$title', '', '$category_list', '$alt_name', '$allow_comm', '$approve', '$allow_main', '$news_fixed', '$allow_rating', '$allow_br', '1', '" . $_POST['tags'] . "')" );
Заменяем на:
$db->query( "INSERT INTO " . PREFIX . "_post (date, autor, short_story, full_story, xfields, title, keywords, category, alt_name, allow_comm, approve, allow_main, fixed, allow_rate, allow_br, flag, tags, short_tpl, full_tpl) values ('$thistime', '$member_id[name]', '$short_story', '$full_story', '$filecontents', '$title', '', '$category_list', '$alt_name', '$allow_comm', '$approve', '$allow_main', '$news_fixed', '$allow_rating', '$allow_br', '1', '" . $_POST['tags'] . "', '$short_tpl', '$full_tpl')" );
Находим:
$tpl->set( '{category}', $cats );
Ниже вствляем:
        $templ = '<option value="">---</option>';
        
        foreach ( $template as $value ) $templ .= '<option value="' . $value . '">' . $value . '.tpl</option>';
        
        $tpl->set( '{short-tpl}', '<select name="short_tpl" id="short_tpl">' . $templ . '</select>' );
        $tpl->set( '{full-tpl}', '<select name="full_tpl" id="full_tpl">' . $templ . '</select>' );
В шаблон, добавления новостей addnews.tpl добавляем теги {short-tpl} - для выбора шаблона для краткой новости и {full-tpl} для выбора шаблона полной новости.

4. Открываем engine/engine.php
Находим все запросы содержащие:
SELECT id, autor,
Заменяем этот участок на:
SELECT id, autor, short_tpl, full_tpl,
P.S> Если не хотите мучится с запросами, то можно сделать по другому (Но лучше сделайте замену вручную):
5. Открываем engine/modules/show.short.php
Находим:
$sql_result = $db->query( $sql_select );
Выше вствляем:
$sql_select = str_replace( 'autor,', 'autor, short_tpl, full_tpl,', $sql_select );

6. Открываем engine/modules/show.full.php
Находим:
$sql_result = $db->query( $sql_news );
Выше вствляем:
$sql_news = str_replace( 'autor,', 'autor, short_tpl, full_tpl,', $sql_news );

7. Открываем engine/modules/show.full.php
Находим:
        if( isset( $view_template ) and $view_template == "print" ) $tpl->load_template( 'print.tpl' );
        elseif( $category_id and $cat_info[$category_id]['full_tpl'] != '' ) $tpl->load_template( $cat_info[$category_id]['full_tpl'] . '.tpl' );
        else $tpl->load_template( 'fullstory.tpl' );
Заменяем на:
        if( isset( $view_template ) and $view_template == "print" ) $tpl->load_template( 'print.tpl' );
        elseif ( $row['full_tpl'] != '' ) $tpl->load_template( 'show/' . $row['full_tpl'] . '.tpl' );
        elseif( $category_id and $cat_info[$category_id]['full_tpl'] != '' ) $tpl->load_template( $cat_info[$category_id]['full_tpl'] . '.tpl' );
        else $tpl->load_template( 'fullstory.tpl' );

8. Открываем engine/modules/show.short.php
Находим:
    if( isset( $view_template ) and $view_template == "rss" ) {
    } elseif( $category_id and $cat_info[$category_id]['short_tpl'] != '' ) $tpl->load_template( $cat_info[$category_id]['short_tpl'] . '.tpl' );
    else $tpl->load_template( 'shortstory.tpl' );
Заменяем на:
    if( isset( $view_template ) and $view_template == "rss" ) {}
    else
    {
        $template = get_vars( 'template' );

        if ( ! $template )
        {
            $template = array( );
            $template[0] = '';
            
            if( $handle = opendir( $tpl->dir . DIRECTORY_SEPARATOR . 'show' ) )
            {
                while( false !== ( $file = readdir( $handle ) ) )
                {
                    $file = substr( $file, 0, -4 );
                    
                    if ( file_exists( $tpl->dir . DIRECTORY_SEPARATOR . 'show' . DIRECTORY_SEPARATOR . $file . '.tpl' ) )
                        $template[$file] = file_get_contents( $tpl->dir . DIRECTORY_SEPARATOR . 'show' . DIRECTORY_SEPARATOR . $file . '.tpl' );
                }
            
                closedir( $handle );
            }

            set_vars( 'template', $template );
        }
        
        if ( $category_id AND $cat_info[$category_id]['short_tpl'] != '' AND file_exists( $tpl->dir . DIRECTORY_SEPARATOR . $cat_info[$category_id]['short_tpl'] . '.tpl' ) ) $template[0] = file_get_contents( $tpl->dir . DIRECTORY_SEPARATOR . $cat_info[$category_id]['short_tpl'] . '.tpl' );
        elseif ( file_exists( $tpl->dir . DIRECTORY_SEPARATOR . 'shortstory.tpl' ) ) $template[0] = file_get_contents( $tpl->dir . DIRECTORY_SEPARATOR . 'shortstory.tpl' );
        else die( 'Невозможно загрузить шаблон' );
    }
Находим:
    while ( $row = $db->get_row( $sql_result ) ) {
Ниже вствляем:
        if ( $row['short_tpl'] != '' AND $template[$row['short_tpl']] ) $tpl->copy_template = $template[$row['short_tpl']];
        else $tpl->copy_template = $template[0];

9. Вот и все! Теперь при публикации новостей Вы можете выбирать шаблон для нее, в админ панели списки с шаблонами находятся во вкладки "Дополнительно".
Внимание!
Первая загрузка главной страницы, может потребовать некоторое время, так как будет производится кэшеирование шаблонов.
После добавления новых шаблонов в папку show, необходимо очистить кэш сайта.
Чем больше шаблонов в папку show, тем сильнее нагрузка на сервер (Поэтому не загружайте в эту папку не используемые шаблоны).
Если не хотите использовать выбор шаблона при добавлении новостей с сайте не выполняйте 5 пункт.
Другие новости по теме:

Категория: Хаки ----- Просмотров: 2338 ----- Комментариев: 2

Вернуться

  • lockon

  • 16 ноября 2010 03:44
  • Группа: Гости
  • ICQ: --
  • Регистрация: --
  • Комментариев: 0
  • Публикаций: 0
^
Да идейка неплохая , +1 Если бы ещё отдельный show.short.php, show.full.php для категорий, было-бы вообще замечательно. nj
  • zarox

  • 18 ноября 2010 11:23
  • Группа: User
  • ICQ: --
  • Регистрация: 21.05.2010
  • Комментариев: 6
  • Публикаций: 0
^
Ещё бы install.php для автоматической установки и вообще было бы отлично))
А то каждый раз устанавливать данный хак после обновления движка, жесть)