Localization in Nancy without the razor viewengine

前端 未结 2 1147
抹茶落季
抹茶落季 2021-02-08 02:04

For the moment I\'m using razor as my view engine in Nancy.
I can access my resource file like this in razor:

@Text.text.greeting

But I wo

2条回答
  •  醉梦人生
    2021-02-08 02:37

    I now made my own solution because I couldn't use resource files.

    In my model I have a dynamic Text object with the resources in the correct language.
    (the language depends on the current user and is a int)

    public dynamic Text { get; private set; }
    

    At the start I build a static dictionary per language.

    private static Dictionary messages = null;
    

    I created a ResourceDictionary to fill the dynamic object:

    public class ResourceDictionary : DynamicObject
    {
        private Dictionary dictionary;
    
        public ResourceDictionary()
        {
            dictionary = new Dictionary();
        }
    
        public void Add(string key, string value)
        {
            dictionary.Add(key, value);
        }
    
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            string data;
            if (!dictionary.TryGetValue(binder.Name, out data))
            {
                throw new KeyNotFoundException("Key not found!");
            }
    
            result = (string)data;
    
            return true;
        }
    
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (dictionary.ContainsKey(binder.Name))
            {
                dictionary[binder.Name] = (string)value;
            }
            else
            {
                dictionary.Add(binder.Name, (string)value);
            }
    
            return true;
        }
    }
    

提交回复
热议问题