Hi, is it possible to create a universal function to interpolation to any string?
maybe there is a function to pass values to the template one at time?
teplate = "\$str1 \$str2"
function get_text_by_template(teplate; x...)
#?
return text # teplate + x
end
get_text_by_template(teplate; str1 = "Hellow!", str2 = "Need help!") # -> "Hellow! Need help!"
You might want to try some real templating system like https://github.com/jverzani/Mustache.jl.
2 Likes
There is also Formatting.jl
if you are not married to the specific format.
2 Likes
Possibly Printf
too:
using Printf
get_text_by_template(template, x, y) = Printf.format(template, x, y)
template = Printf.Format("%s %s")
str1 = "Hello!"
str2 = "Need help!"
get_text_by_template(template, str1, str2)
# result:
"Hello! Need help!"
I wonder why Printf.format
is neither documented nor exported.
There could easily be
function printf(io::IO, fmt, args...)
format(io, fmt, args...)
end
function printf(T::Type, fmt, args...)
io = StringBuffer()
printf(io, fmt, args...)
T(take!(io))
end
printf(io::IO, fmt::AbstractString, args...) = printf(io, Format(fmt), args...)
printf(fmt, args...) = printf(stdout, fmt, args...)
and this problem would just be gone.
2 Likes
Partly because it’s type unstable and hence relatively slow, I think — in contrast, if you use @printf
or @sprintf
then the Format
object is created at lowering time so it is known to the compiler. So we want to steer people towards the macro interface if possible.
And how often do you printf
in a performance critical context? I feel like this could be solved by a mention in the “Performance tips” section, together with @code_warntype
. Are there no other sub-optimal convenience functions in the language?
Maybe a good midway would be to simplify and document the function, including pointing out the better way to do it, and not exporting it. That way people who run into this can opt in to that loss of performance with using Printf: printf
.
1 Like