I try to write a minimal generator (Phoenix 1.7). Here it is:
defmodule Mix.Tasks.CopyTemplates do
use Mix.Task
@shortdoc "Renders .heex templates with variables and copies them to the specified directories."
def run(_) do
# Path to the source templates
source_path = "priv/templates/example.gen.html/"
app_web_path = "lib/app_web/"
prefix = "product"
# Define files and their respective destination paths
file_destinations = %{
"index.html.heex" => "#{app_web_path}/controllers/#{prefix}_html/index.html.heex"
}
# Variables to be inserted into the templates
assigns = %{
route_prefix: "/products",
human_singular: "Product",
human_plural: "Products",
schema_singular: "product"
}
Enum.each(file_destinations, fn {source_file, dest_file} ->
# Read the content of the source file
template = File.read!(source_path <> source_file)
# Render the template with the assigns using Phoenix.View
content = Phoenix.View.render_to_string({Phoenix.View, template}, assigns)
# Ensure the destination directory exists
dest_dir = Path.dirname(dest_file)
File.mkdir_p!(dest_dir)
# Save the rendered content to the destination file
File.write!(dest_file, content)
end)
IO.puts("Templates have been successfully rendered and copied!")
end
end
When I run it I get this error:
warning: Phoenix.View.render_to_string/2 is undefined (module Phoenix.View is not available or is yet to be defined)
lib/mix/tasks/copy_templates.ex:30
** (UndefinedFunctionError) function Phoenix.View.render_to_string/2 is undefined (module Phoenix.View is not available)
I guess the problem is content = Phoenix.View.render_to_string({Phoenix.View, template}, assigns)
but how can I fix it?