Template file evaluation in flutter

旧街凉风 提交于 2021-02-11 12:12:27

问题


I am loading some text from a file in a String variable in my code. This text has certain values that must be filled-in dynamically from a Map. When I use a String directly in my code, it works fine as desired. But when the same string is loaded from the file, it does not perform the required string interpolation.

Consider this for string interpolation -

  String parseText(Map<String, dynamic> ctx){
    return "My name is ${ctx['employee'].name} and I joined today, ${ctx['today']}";
  }

This works just fine with correct employee name and date. But when I have this string loaded from a file (string loading from a file is working fine by itself) - the text is is returned without substitution, see this -

  String parseText(Map<String, dynamic> ctx){
    String text = getTextFromFile(String path); //working fine  
    // Can I do something here to get the text evaluated/interpolated correctly?    
    return text; //returns text as-it-is, without interpolation/evaluation
  }

I have already seen this solution in dart, and it is quite similar to what I am doing, but when I replace the text/string with my string loaded from the file, it doesn't perform necessary string interpolation. I am new to flutter, am I missing something obvious here?

How can I get string interpolation working with text loaded from file?


回答1:


String interpolation requires using string literals. This essentially makes it syntactic sugar performed at compilation time. You cannot perform string interpolation from an arbitrary String object since that would allow arbitrary code execution, a security vulnerability.

If you need to generate strings from dynamically-generated templates, you will need to create your own parser.




回答2:


This is what I figured out from this answer -

String interpolation only works with hardcoded strings.

However, I found template package mustache that handles this problem quite well and it should help anyone trying file-based string interpolation (actually, template evaluation) with flutter/dart.

This template can be stored in a file (dot-notation works for objects if they are populated as maps in the context) like this -

My name is {{employee.name}}, aged {{employee.age}} years, 
and I joined today - {{today}}.

And context would be -

final ctx = {
   "employee": employee(),
   "today": getToday(),  //function call to get today's date
};

The template evaluation would be -

Template t = new Template(getFileText());
print(t.renderString(ctx));

I hope mustache would help someone looking for similar solution.



来源:https://stackoverflow.com/questions/62326641/template-file-evaluation-in-flutter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!