We give a systematic method for discretizing Hamiltonian partial differential equations (PDEs) with constant symplectic structure, while preserving their energy exactly. The same method, applied to PDEs with constant dissipative structure, also preserves the correct monotonic decrease of energy. The method is illustrated by many examples. In the Hamiltonian case these include: the sine-Gordon, Korteweg-de Vries, nonlinear Schrodinger, (linear) time-dependent Schrodinger, and Maxwell equations. In the dissipative case the examples are: the Allen-Cahn, Cahn-Hilliard, Ginzburg-Landau, and heat equations.