Blog Archive

Saturday 20 July 2013

Symfony 2 pluralization russian twig extension

I has the problem with symfony2, that I couldn't translate plural forms in a proper way inside the twig templates.
There are only two options with the standard symfony2  trans tag and transchoice tag. They are described here.

trans tag allows to translate a simple string
transchoice is something more complex. It allows to translate string based on number you provide. Simple logic looks like this.

1 - I have just one apple
2 - I have couple
3 - There is enough for three of us
4 - I have many apples
5
6
..
100 - I have many apples

So basically when you use transchoice you have to provide explicit translation and explicit range.
With russian language it is different

the formula for suffixes in russian looks like this:
<?php
(($number % 10 == 1) && ($number % 100 != 11))
    ? 0
    : ((($number % 10 >= 2)
        && ($number % 10 <= 4)
        && (($number % 100 < 10)
        || ($number % 100 >= 20)))
            ? 1
            : 2
);
?>

The problem with symfony2 is that it does not provide any mechanism to use it. If you use plain twig, it will have the translplural tag. but it is not included in symfony2, so I had to write my own.

<?php 
namespace YourBundleName\TwigExtensions; 
use Symfony\Bundle\FrameworkBundle\Translation\Translator; 
use Twig_Extension; 
 
class TransPlural extends Twig_Extension 
{ 
    protected $translator; 
    public function __construct(Translator $translator) 
    { 
        $this->translator = $translator; 
    } 
 
    public function getFilters() 
    { 
        return array( 
            new \Twig_SimpleFilter('transplural', array($this, 'transplural')), 
        ); 
    } 
 
    public function transplural($string, $number) 
    { 
        $translated = $this->translator->trans( 
            '%d '.$string, 
            array('%d' => $number) 
        ); 
        $type = (($number % 10 == 1) && ($number % 100 != 11)) 
        ? 0 
        : ((($number % 10 >= 2) 
            && ($number % 10 <= 4) 
            && (($number % 100 < 10) 
                || ($number % 100 >= 20))) 
            ? 1 
            : 2 
        ); 
        //this if condition here because on some servers $this->translator->tran
        //was returning wrong strings
        if (strpos($translated,"{")===false) 
        { 
            $translated_array = explode("|", $translated); 
            return $translated_array[$type]; 
        } 
        else 
        { 
            return $this->translator->transChoice($translated,  $type, array("%count%"=>$type)); 
 
        } 
 
    } 
 
    /** 
     * Returns the name of the extension. 
     * 
     * @return string The extension name 
     */ 
    public function getName() 
    { 
        return "translate_plural_russian"; 
    } 
}


And additionally you need to add following lines to the services.xml

<service id="twig.plural_extension" class="YourBundleName\TwigExtensions\TransPlural">
    <tag name="twig.extension" />
    <argument type="service" id="translator"></argument>
</service>

And then you will be able to use transplural tag inside your twig templates like this:

{{ "string to be pluralized"|transplural(number) }} 

Tuesday 11 June 2013

Django localization settings

This examle shows all the settings that you need to put in your settings file in order to have the Django 1.5 to run in russian language.

ugettext = lambda s: s
LANGUAGES = (
    ('ru', 'Russian'),
)
LOCALE_PATHS = (
    PROJECT_PATH+'/locale', #this is the place where the language files stored
)
LANGUAGE_CODE = 'ru'



If any of these missing, it will not work

Wednesday 10 April 2013

Save button for ckeditor using ajax

The task was to use inline ckeditor in order to edit div contents and save by sending ajax request to the server.
I have stuck to a problem that ckeditor save button did not appear on the toolbar. So here is a solution for that. The most important part is highlighted with bold.
Just replace the "save" plugin contents. You can find it in ckeditor/plugins/save/plugin.js


(function() {
 var saveCmd = { modes:{wysiwyg:1,source:1 },
  readOnly: 1,

  exec: function( editor ) {
            var data = editor.getData();
            jQuery.post(editor.config.saveSubmitURL,
                        {text: data},
                        function(response){
                           alert('Data sent to server!!!');
                        });
  }
 };

 var pluginName = 'save';

 // Register a plugin named "save".
 CKEDITOR.plugins.add( pluginName, {
  lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en-au,en-ca,en-gb,en,eo,es,et,eu,fa,fi,fo,fr-ca,fr,gl,gu,he,hi,hr,hu,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt-br,pt,ro,ru,sk,sl,sr-latn,sr,sv,th,tr,ug,uk,vi,zh-cn,zh', // %REMOVE_LINE_CORE%
  icons: 'save', // %REMOVE_LINE_CORE%
  init: function( editor ) {
   var command = editor.addCommand( pluginName, saveCmd );
   //command.modes = { wysiwyg: !!( editor.element.$.form ) };

   editor.ui.addButton( 'Save', {
    label: editor.lang.save.toolbar,
    command: pluginName,
    toolbar: 'clipboard,50'
   });
  }
 });
})();

Additionally you will need to update the config.js file for the ckeditor and add the following lines

config.saveSubmitURL = 'URL_TO_YOUR_SERVER_SCRIPT.php';

And you are done.

The problem was that "save" plugin was only working in the "replace" mode. When ckeditor replaces textareas on the page with the editor. But is was not working in the inline mode. When you use ckeditor in order to edit contents of the div tags.

UPD: There is working solution on stackoverflow posted by user kasper Taeymans

Tuesday 5 February 2013

Принуждение судей к более законному рассмотрению судебных процессов в Кыргзыстане

Сегодня посетил Мастер-класс "Уголовное преследование должностных лиц", на котором Нурбек Токтакунов рассказывал о том как можно привлечь государственных служащих к уголовной ответственности в случае применения неправомерных действий к гражданам нашей страны.

Во время данного мероприятия у меня из головы не выходили пара вопросов. "А как же можно заставить судей более объективно и тщательно относится к своей работе? И как можно в них развить культуру более ответственного отношения к рассмотрению судебных дел?".

Monday 16 January 2012

Django - Adding row to the admin list with the totals and averages of given fields

Once a while a wild ticked occurred for one of the projects I was developing.
The issue was that they needed a rows with the totals and averages to be displayed at the end of the table in the admin changelist view for particular fields.
So here how it works




Saturday 5 November 2011

Пойдемте в гости!

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

На сегодняшний день все больше замечаю как многие из друзей и знакомых перестали ходить в гости домой. Сейчас все ходят в кафе и рестораны. А почему бы и нет? Готовить и убирать то не надо. Отвалил сумму из кармана и все в порядке.
Что то я немного отошел. Вспомните как в детстве наши родители приглашали домой своих друзей, коллег, и просто знакомых. Как много радости было тогда. Как стол ломился от всяких конфет, вкусняшек и приходилось тайком оттуда таскать это все по немного пока мама была занята на кухне подготовкой. А когда тебя заметят тут же валишь в детскую комнату с наживой и сидишь там тихо, типа ничего и не происходило и если повезет то и конфетку покушаешь. А мама там ругается чтобы никто к столу не подходил. Ведь гости придут. А ты потом снова тайком в зал за добычей. И так пока не надоест.

И вот долгожданный момент когда приходят первые гости, все здороваются, тут же начинаются всякие разговоры о детях, о семье, да и вообще о всяких делах. Все такие радостные. А если повезет кто нибудь из гостей приведет сына своего или дочку, очень хорошего твоего друга. И будете вы вместе тусить. А ты еще показываешь другу дома все, говоришь о новостях и чего нового тебе с прошлого раза родители купили. И начинаете во все это играться.

Потихоньку собираются все гости и начинается главная часть, где приносят покушать первое, потом второе, еще и десерт. Сколько радости то!

А потом в следующий раз уже вы идете в гости, мама тебя наряжает. И говорит чтобы не было как в прошлый раз, что то там поломали. Хе хе.
Но это все детство.

Самое главное в этом всем - это атмосфера той радости которую мы испытывали когда к нам приходил гости, и мы ходили к кому-нибудь.
Теперь то ведь мы все реже ходим в гости. И это как то грустно.
Давайте чаще навещать друг друга. Но не где-нибудь в кафе. А дома.