Template Haskell allows code to be generated at compile time by splicing quasi quotations into the abstract syntax tree. It works by running Haskell code that constructs syntax expressions and splicing the results into the code being compiled. This allows features like generating boilerplate code, domain-specific languages, and compile-time metaprogramming in Haskell.